<?php

/////////
//汇报文件生成上传
////////

function huibao_file_create_page(){
	 drupal_set_title('汇报文件生成');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('huibao_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function huibao_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '汇报文件上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function huibao_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('huibao_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'huibao_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function huibao_file_create_fund_page($fund_id){
	 drupal_set_title('汇报文件');
	 $html = '';
	 $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
	 $queryResult = db_query($query, array($fund_id));
	 foreach($queryResult as $result){
	  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
	 }
	 $render_array = array(
	   		'#markup' => $html,
     );
	 
     $form = drupal_get_form('huibao_file_create_fund_form',$fund_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function huibao_file_create_fund_form($form, &$form_state,$fund_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $fund_id);
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '汇报文件上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function huibao_file_create_fund_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('huibao_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'huibao_file/fundlist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//汇报文件生成浏览
function huibao_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;
   if(user_access('upload edit files')){
 		$page_content .= l('编辑','huibao_file/edit/'.$perid) .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
  }
  $page_content .= l('返回列表','huibao_file/list') . '<br />'. '<br />';
  $query = "SELECT id, name,url,timestamp,remark,user_id,upload_name FROM " .
           "{huibao_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;
 
  foreach($queryResult as $links){
   	  $ifempty = FALSE;
	  $page_content .= '<h5>汇报文件材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该汇报文件材料信息.";
  }
  return $page_content;
}

//汇报文件生成编辑
function huibao_file_edit_page($perid) {
  $page_content = '';
  $page_content .= l('返回列表','huibao_file/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $page_content .= l('浏览','huibao_file/view/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('汇报文件管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{huibao_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('huibao_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已上传汇报文件:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('huibao_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function huibao_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{huibao_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['huibao_file_edit_form']['name'])?$_SESSION['huibao_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['huibao_file_edit_form']['upload_name'])?$_SESSION['huibao_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交汇报文件材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['huibao_file_edit_form']['remark'])?$_SESSION['huibao_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('huibao_file_edit_form_delete'),
	  );
		  
  return $form;
}

function huibao_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('huibao_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'huibao_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('huibao_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'huibao_file/view/'.$values['bid'];
	}
}

function huibao_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['huibao_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['huibao_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'huibao_file/delete/'.$values['bid'];
}

//汇报文件生成删除
function huibao_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除汇报文件内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('huibao_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function huibao_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('huibao_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function huibao_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['huibao_file_edit_form'])){
		  	$form_state['redirect'] = 'huibao_file/list';
	  }else{
		  $values = $_SESSION['huibao_file_edit_form'];
		  unset($_SESSION['huibao_file_edit_form']);
		  $form_state['redirect'] = 'huibao_file/edit/'.$values['bid'];
	  }
}

function huibao_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['huibao_file_edit_form'])){
		  $form_state['redirect'] = 'huibao_file/list';
	  }else{
		  $values = $_SESSION['huibao_file_edit_form'];
		  unset($_SESSION['huibao_file_edit_form']); 
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('huibao_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'huibao_file/list';

	  }

}

//汇报文件生成列表
function huibao_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('返回列表', 'huibao_file/fund').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传汇报文件', 'huibao_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传汇报文件材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('huibao_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'huibao_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','huibao_file/edit/'. $node->id),
        l('删除','huibao_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}
//汇报文件列表
function huibao_file_fundlist_perpage($fund_id) {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('返回基金选择列表', 'huibao_file/fund'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传汇报文件', 'huibao_file/create/fundid/'.$fund_id).'<br><br>';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('huibao_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'huibao_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','huibao_file/edit/'. $node->id),
        l('删除','huibao_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//出资人设置基金选择入口
function huibao_file_fundlist_page() {
 $html = '';
 $html .= l('其他汇报文件列表', 'huibao_file/list').'<br><br>';
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '汇报文件管理', 'field' => 'shixiang_set'),
      array('data' => '上传汇报文件', 'field' => 'shixiang_upload'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
          $title = l('汇报文件管理', 'huibao_file/fundlist/'.$node->id);
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        $title,
	        l('新建汇报文件', 'huibao_file/create/fundid/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

/////////
//理事会决策记录上传
////////

function lishihuijuece_file_create_page(){
	 drupal_set_title('理事会决策记录');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('lishihuijuece_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function lishihuijuece_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '理事会决策记录上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function lishihuijuece_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('lishihuijuece_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'lishihuijuece_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function lishihuijuece_file_create_fund_page($fund_id){
	 drupal_set_title('理事会决策记录');
	 $html = '';
	 $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
	 $queryResult = db_query($query, array($fund_id));
	 foreach($queryResult as $result){
	  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
	 }
	 $render_array = array(
	   		'#markup' => $html,
     );
	 
     $form = drupal_get_form('lishihuijuece_file_create_fund_form',$fund_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function lishihuijuece_file_create_fund_form($form, &$form_state,$fund_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $fund_id);
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '理事会决策记录上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function lishihuijuece_file_create_fund_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('lishihuijuece_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'lishihuijuece_file/fundlist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//理事会决策记录浏览
function lishihuijuece_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;
  if(user_access('upload edit files')){
 		$page_content .= l('编辑','lishihuijuece_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  }
  $page_content .= l('返回列表','lishihuijuece_file/list') . '<br />'. '<br />';
  $query = "SELECT id, name,url,timestamp,remark,user_id,upload_name FROM " .
           "{lishihuijuece_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;
  
  foreach($queryResult as $links){
   	  $ifempty = FALSE;
	  $page_content .= '<h5>理事会决策记录材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该理事会决策记录材料信息.";
  }
  return $page_content;
}

//理事会决策记录编辑
function lishihuijuece_file_edit_page($perid) {
  $page_content = '';
  $page_content .= l('返回列表','lishihuijuece_file/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $page_content .= l('浏览','lishihuijuece_file/view/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('理事会决策记录管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{lishihuijuece_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('lishihuijuece_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已上传理事会决策记录:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('lishihuijuece_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function lishihuijuece_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{lishihuijuece_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['lishihuijuece_file_edit_form']['name'])?$_SESSION['lishihuijuece_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['lishihuijuece_file_edit_form']['upload_name'])?$_SESSION['lishihuijuece_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交理事会决策记录材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['lishihuijuece_file_edit_form']['remark'])?$_SESSION['lishihuijuece_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('lishihuijuece_file_edit_form_delete'),
	  );
		  
  return $form;
}

function lishihuijuece_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('lishihuijuece_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'lishihuijuece_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('lishihuijuece_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'lishihuijuece_file/view/'.$values['bid'];
	}
}

function lishihuijuece_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['lishihuijuece_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['lishihuijuece_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'lishihuijuece_file/delete/'.$values['bid'];
}

//理事会决策记录删除
function lishihuijuece_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除理事会决策记录内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('lishihuijuece_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function lishihuijuece_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('lishihuijuece_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function lishihuijuece_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['lishihuijuece_file_edit_form'])){
		  	$form_state['redirect'] = 'lishihuijuece_file/list';
	  }else{
		  $values = $_SESSION['lishihuijuece_file_edit_form'];
		  unset($_SESSION['lishihuijuece_file_edit_form']);
		  $form_state['redirect'] = 'lishihuijuece_file/edit/'.$values['bid'];
	  }
}

function lishihuijuece_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['lishihuijuece_file_edit_form'])){
		  $form_state['redirect'] = 'lishihuijuece_file/list';
	  }else{
		  $values = $_SESSION['lishihuijuece_file_edit_form'];
		  unset($_SESSION['lishihuijuece_file_edit_form']);
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('lishihuijuece_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'lishihuijuece_file/list';

	  }

}

//理事会决策记录列表
function lishihuijuece_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('上传理事会决策记录', 'lishihuijuece_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传理事会决策记录材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('lishihuijuece_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'lishihuijuece_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','lishihuijuece_file/edit/'. $node->id),
        l('删除','lishihuijuece_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//理事会决策列表
function lishihuijuece_file_fundlist_perpage($fund_id) {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('返回基金选择列表', 'lishihuijuece_file/fund'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传理事会决策', 'lishihuijuece_file/create/fundid/'.$fund_id).'<br><br>';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('lishihuijuece_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'lishihuijuece_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','lishihuijuece_file/edit/'. $node->id),
        l('删除','lishihuijuece_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//出资人设置基金选择入口
function lishihuijuece_file_fundlist_page() {
 $html = '';
 $html .= l('其他理事会决策列表', 'lishihuijuece_file/list').'<br><br>';
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '理事会决策管理', 'field' => 'shixiang_set'),
      array('data' => '上传理事会决策', 'field' => 'shixiang_upload'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
          $title = l('理事会决策管理', 'lishihuijuece_file/fundlist/'.$node->id);
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        $title,
	        l('新建理事会决策', 'lishihuijuece_file/create/fundid/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//理事会决策目录列表
function lishihuijuece_list_page() {
  // content variable that will be returned for display
  /*
  $html = '';
  $html .=  l('上传汇报文件', 'huibao_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传汇报文件材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('huibao_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'huibao_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','huibao_file/edit/'. $node->id),
        l('删除','huibao_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  
  
  $html .=  l('上传理事会决策记录', 'lishihuijuece_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传理事会决策记录材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('lishihuijuece_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'lishihuijuece_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','lishihuijuece_file/edit/'. $node->id),
        l('删除','lishihuijuece_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
	  
  */
  $html = '';
// $html .= l('其他理事会决策列表', 'lishihuijuece_file/list').'<br><br>';
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '汇报文件管理', 'field' => 'shixiang_set'),
      array('data' => '上传汇报文件', 'field' => 'shixiang_upload'),
      array('data' => '理事会决策管理', 'field' => 'shixiang_set'),
      array('data' => '上传理事会决策', 'field' => 'shixiang_upload'),
      array('data' => '进入合作谈判名单设置', 'field' => 'to_hezuotanpan_list'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        l('汇报文件管理', 'huibao_file/fundlist/'.$node->id),
	        l('新建汇报文件', 'huibao_file/create/fundid/'.$node->id),
	        l('理事会决策管理', 'lishihuijuece_file/fundlist/'.$node->id),
	        l('新建理事会决策', 'lishihuijuece_file/create/fundid/'.$node->id),
	        l('名单管理', 'guidingfund/totanpanlist_page/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}



/////////
//谈判要点对比上传
////////

function tanpanyaodian_file_create_page(){
	 drupal_set_title('谈判要点对比');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('tanpanyaodian_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function tanpanyaodian_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '谈判要点对比上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function tanpanyaodian_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('tanpanyaodian_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'tanpanyaodian_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//谈判要点对比浏览
function tanpanyaodian_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;
  if(user_access('upload edit files')){
 		$page_content .= l('编辑','tanpanyaodian_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  }
  $page_content .= l('返回列表','tanpanyaodian_file/list') . '<br />'. '<br />';
  $query = "SELECT id, name,url,timestamp,remark,user_id,upload_name FROM " .
           "{tanpanyaodian_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;
  
  foreach($queryResult as $links){
   	  $ifempty = FALSE;
	  $page_content .= '<h5>谈判要点对比材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该谈判要点对比材料信息.";
  }
  return $page_content;
}

//谈判要点对比编辑
function tanpanyaodian_file_edit_page($perid) {
  $page_content = '';
  $page_content .= l('返回列表','tanpanyaodian_file/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $page_content .= l('浏览','tanpanyaodian_file/view/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('谈判要点对比管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{tanpanyaodian_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('tanpanyaodian_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已上传谈判要点对比:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('tanpanyaodian_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function tanpanyaodian_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{tanpanyaodian_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['tanpanyaodian_file_edit_form']['name'])?$_SESSION['tanpanyaodian_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['tanpanyaodian_file_edit_form']['upload_name'])?$_SESSION['tanpanyaodian_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交谈判要点对比材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['tanpanyaodian_file_edit_form']['remark'])?$_SESSION['tanpanyaodian_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('tanpanyaodian_file_edit_form_delete'),
	  );
		  
  return $form;
}

function tanpanyaodian_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('tanpanyaodian_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'tanpanyaodian_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('tanpanyaodian_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'tanpanyaodian_file/view/'.$values['bid'];
	}
}

function tanpanyaodian_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['tanpanyaodian_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['tanpanyaodian_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'tanpanyaodian_file/delete/'.$values['bid'];
}

//谈判要点对比删除
function tanpanyaodian_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除谈判要点对比内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('tanpanyaodian_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function tanpanyaodian_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('tanpanyaodian_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function tanpanyaodian_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['tanpanyaodian_file_edit_form'])){
		  	$form_state['redirect'] = 'tanpanyaodian_file/list';
	  }else{
		  $values = $_SESSION['tanpanyaodian_file_edit_form'];
		  unset($_SESSION['tanpanyaodian_file_edit_form']);
		  $form_state['redirect'] = 'tanpanyaodian_file/edit/'.$values['bid'];
	  }
}

function tanpanyaodian_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['tanpanyaodian_file_edit_form'])){
		  $form_state['redirect'] = 'tanpanyaodian_file/list';
	  }else{
		  $values = $_SESSION['tanpanyaodian_file_edit_form'];
		  unset($_SESSION['tanpanyaodian_file_edit_form']);
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('tanpanyaodian_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'tanpanyaodian_file/list';

	  }

}

//谈判要点对比列表
function tanpanyaodian_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('上传谈判要点对比', 'tanpanyaodian_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传谈判要点对比材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('tanpanyaodian_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'tanpanyaodian_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','tanpanyaodian_file/edit/'. $node->id),
        l('删除','tanpanyaodian_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

/////////
//过程文件储存与备忘上传
////////

function guochengwenjian_file_create_page(){
	 drupal_set_title('过程文件储存与备忘');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('guochengwenjian_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function guochengwenjian_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '过程文件储存与备忘上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function guochengwenjian_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('guochengwenjian_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'guochengwenjian_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//过程文件储存与备忘浏览
function guochengwenjian_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;
  if(user_access('upload edit files')){
 		$page_content .= l('编辑','guochengwenjian_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  }
  $page_content .= l('返回列表','guochengwenjian_file/list') . '<br />'. '<br />';
  $query = "SELECT id, name,url,timestamp,remark,user_id,upload_name FROM " .
           "{guochengwenjian_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;
  
  foreach($queryResult as $links){
   	  $ifempty = FALSE;
	  $page_content .= '<h5>过程文件储存与备忘材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该过程文件储存与备忘材料信息.";
  }
  return $page_content;
}

//过程文件储存与备忘编辑
function guochengwenjian_file_edit_page($perid) {
  $page_content = '';
  $page_content .= l('返回列表','guochengwenjian_file/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $page_content .= l('浏览','guochengwenjian_file/view/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('过程文件储存与备忘管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{guochengwenjian_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('guochengwenjian_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已上传过程文件储存与备忘:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('guochengwenjian_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function guochengwenjian_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{guochengwenjian_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['guochengwenjian_file_edit_form']['name'])?$_SESSION['guochengwenjian_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['guochengwenjian_file_edit_form']['upload_name'])?$_SESSION['guochengwenjian_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交过程文件储存与备忘材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['guochengwenjian_file_edit_form']['remark'])?$_SESSION['guochengwenjian_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('guochengwenjian_file_edit_form_delete'),
	  );
		  
  return $form;
}

function guochengwenjian_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
				
			if($filemanagedid>0){
			   $file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }	
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('guochengwenjian_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'guochengwenjian_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('guochengwenjian_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'guochengwenjian_file/view/'.$values['bid'];
	}
}

function guochengwenjian_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['guochengwenjian_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['guochengwenjian_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'guochengwenjian_file/delete/'.$values['bid'];
}

//过程文件储存与备忘删除
function guochengwenjian_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除过程文件储存与备忘内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('guochengwenjian_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function guochengwenjian_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('guochengwenjian_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function guochengwenjian_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['guochengwenjian_file_edit_form'])){
		  	$form_state['redirect'] = 'guochengwenjian_file/list';
	  }else{
		  $values = $_SESSION['guochengwenjian_file_edit_form'];
		  unset($_SESSION['guochengwenjian_file_edit_form']);
		  $form_state['redirect'] = 'guochengwenjian_file/edit/'.$values['bid'];
	  }
}

function guochengwenjian_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['guochengwenjian_file_edit_form'])){
		  $form_state['redirect'] = 'guochengwenjian_file/list';
	  }else{
		  $values = $_SESSION['guochengwenjian_file_edit_form'];
		  unset($_SESSION['guochengwenjian_file_edit_form']);
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('guochengwenjian_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'guochengwenjian_file/list';

	  }

}

//过程文件储存与备忘列表
function guochengwenjian_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('上传过程文件储存与备忘', 'guochengwenjian_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传过程文件储存与备忘材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('guochengwenjian_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'guochengwenjian_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','guochengwenjian_file/edit/'. $node->id),
        l('删除','guochengwenjian_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//合作谈判列表
function hezuotanpan_list_page() {
  // content variable that will be returned for display
  $html = '';
  
  $html .=  l('上传谈判要点对比', 'tanpanyaodian_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传谈判要点对比材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('tanpanyaodian_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'tanpanyaodian_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','tanpanyaodian_file/edit/'. $node->id),
        l('删除','tanpanyaodian_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
	  
	  
  $html .=  l('上传过程文件储存与备忘', 'guochengwenjian_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传过程文件储存与备忘材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('guochengwenjian_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'guochengwenjian_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','guochengwenjian_file/edit/'. $node->id),
        l('删除','guochengwenjian_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

/////////
//投资协议章程上传
////////

function touzixieyi_file_create_page(){
	 drupal_set_title('投资协议章程');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('touzixieyi_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function touzixieyi_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '投资协议章程上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function touzixieyi_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('touzixieyi_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'beitouqiye_id' => 0,
			  		     ))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'touzixieyi_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function touzixieyi_file_create_qiye_page($qiye_id){
	 drupal_set_title('投资协议章程');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('touzixieyi_file_create_qiye_form',$qiye_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function touzixieyi_file_create_qiye_form($form, &$form_state,$qiye_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $qiye_id);
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '投资协议章程上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function touzixieyi_file_create_qiye_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('touzixieyi_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'beitouqiye_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'touzixieyi_file/qiyelist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//传入投资章程id
function touzixieyi_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;

  $query = "SELECT id, name, url,timestamp,remark,user_id,upload_name,beitouqiye_id FROM " .
           "{touzixieyi_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;
  if(user_access('upload edit files')){
 		$page_content .= l('编辑','touzixieyi_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
  }
  foreach($queryResult as $links){
  	  $page_content .= l('返回列表','touzixieyi_file/qiyelist/'.$links->beitouqiye_id) . '<br />'. '<br />';
   	  $ifempty = FALSE;
	  $page_content .= '<h5>投资协议章程材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该投资协议章程材料信息.";
  }
  return $page_content;
}

//投资协议章程编辑
function touzixieyi_file_edit_page($perid) {
  $page_content = '';

  $page_content .= l('浏览','touzixieyi_file/view/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 	
  drupal_set_title('投资协议章程管理');
	 
  $query = "SELECT id,name, url,beitouqiye_id FROM " .
           "{touzixieyi_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('touzixieyi_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
 	     $page_content .= l('返回列表','touzixieyi_file/qiyelist/'.$links->beitouqiye_id) . '<br />'. '<br />';
	 	 $page_content .= '<h5>已上传投资协议章程:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('touzixieyi_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function touzixieyi_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{touzixieyi_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['touzixieyi_file_edit_form']['name'])?$_SESSION['touzixieyi_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['touzixieyi_file_edit_form']['upload_name'])?$_SESSION['touzixieyi_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交投资协议章程材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['touzixieyi_file_edit_form']['remark'])?$_SESSION['touzixieyi_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('touzixieyi_file_edit_form_delete'),
	  );
		  
  return $form;
}

function touzixieyi_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('touzixieyi_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'touzixieyi_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('touzixieyi_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'touzixieyi_file/view/'.$values['bid'];
	}
}

function touzixieyi_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['touzixieyi_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['touzixieyi_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'touzixieyi_file/delete/'.$values['bid'];
}

//投资协议章程删除
function touzixieyi_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除投资协议章程内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('touzixieyi_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function touzixieyi_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('touzixieyi_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function touzixieyi_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['touzixieyi_file_edit_form'])){
		  	$form_state['redirect'] = 'touzixieyi_file/list';
	  }else{
		  $values = $_SESSION['touzixieyi_file_edit_form'];
		  unset($_SESSION['touzixieyi_file_edit_form']);
		  $form_state['redirect'] = 'touzixieyi_file/edit/'.$values['bid'];
	  }
}

function touzixieyi_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['touzixieyi_file_edit_form'])){
		  $form_state['redirect'] = 'touzixieyi_file/fundlist';
	  }else{
	  	  
		  $values = $_SESSION['touzixieyi_file_edit_form'];
		  unset($_SESSION['touzixieyi_file_edit_form']);
          $query = "SELECT beitouqiye_id FROM " .
           "{touzixieyi_file_info} where id = ?";
		  $queryResult = db_query($query, array($values['bid']));
		  $qiyeid ='';
		  foreach ($queryResult as $links ) {
				  $qiyeid = $links->beitouqiye_id;
		  }
          $file = file_load($values['file_managed_id']);
		  if($file!=NULL){
			 file_delete($file);
		  }
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('touzixieyi_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		 $form_state['redirect'] = 'touzixieyi_file/qiyelist/'.$qiyeid;

	  }

}

//投资协议章程列表
function touzixieyi_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .= l('基金选择列表', 'touzixieyi_file/fundlist'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传投资协议章程', 'touzixieyi_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('touzixieyi_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('beitouqiye_id',0,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'touzixieyi_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','touzixieyi_file/edit/'. $node->id),
        l('删除','touzixieyi_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//传入企业id
function touzixieyi_file_qiyelist_perpage($qiye_id) {
  // content variable that will be returned for display
  $html = '';
  $query = "SELECT  fund_id ,company_name FROM " .
           "{beitouqiye_info} where id = ?";
  $queryResult = db_query($query, array($qiye_id));
  $company_name = '';
  foreach ($queryResult as $result) {
        $html .= l('企业选择列表', 'touzixieyi_file/qiye/'.$result->fund_id). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	    $company_name = $result->company_name;
  }
  $html .=  l('上传投资协议章程', 'touzixieyi_file/create/qiyeid/'.$qiye_id).'<br><br>';
  $html .=  $company_name;
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('touzixieyi_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('beitouqiye_id',$qiye_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'touzixieyi_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','touzixieyi_file/edit/'. $node->id),
        l('删除','touzixieyi_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//企业选择入口
function touzixieyi_file_qiyelist_page($fund_id) {
  $html = '';	
  $html .= l('返回基金列表','touzixieyi_file/fundlist/') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
  $html .= l('添加被投企业信息','beitouqiye/create/'.$fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .= l('导出','beitouqiye/exportcsv/'.$fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  'custom_css' => drupal_get_path('module','my_module').'/css/print.css',
  );

  $html .= area_print_form($options). '<br />'. '<br />';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  $html .= '<div id="printable_div">';
  $round_num = 1;
  $header = array(
      array('data' => '序号'),
      array('data' => '被投企业名称', 'field' => 'company_name'),
      array('data' => '投资时间', 'field' => 'touzi_timestamp'),
      array('data' => '投资额(万元)', 'field' => 'touzi_money'),
      array('data' => '占股比例', 'field' => 'zhangu_percentage'),
      array('data' => '发展阶段', 'field' => 'fazhanjieduan'),
      array('data' => '投资协议章程管理'),
      );
  $query = db_select('beitouqiye_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(20)//20 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'company_name',
      'touzi_timestamp',
      'touzi_money',
      'zhangu_percentage',
      'fazhanjieduan',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  $_serial_num = 1;
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        $_serial_num,
        l($node->company_name, 'beitouqiye/list/'. $node->id),
        format_date($node->touzi_timestamp, 'custom', 'Y-m-d'),
        $node->touzi_money,
        $node->zhangu_percentage,
        $node->fazhanjieduan,
         l('进入', 'touzixieyi_file/qiyelist/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有被投企业信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= '</div>';
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  
  return ($html); 
}

//投资协议章程设置基金选择入口
function touzixieyi_file_fundlist_page() {
 $html = '';
 
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '投资协议章程设置', 'field' => 'beitouqiye_set'),
      
      //array('data' => '被投企业资本到位记录列表', 'field' => 'beitouqiye_set'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
          $title = l('投资协议章程设置', 'touzixieyi_file/qiye/'.$node->id);
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        $title,
	        //l('资本到位', 'zibendaowei/jilu/ren_fund/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

/////////
//已投企业重大事项
////////

function qiye_zdsx_file_create_page(){
	 drupal_set_title('企业重大事项');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('qiye_zdsx_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function qiye_zdsx_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '企业重大事项上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function qiye_zdsx_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('qiye_zdsx_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'beitouqiye_id' => 0,
			  		     ))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'qiye_zdsx_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}
//传入企业id
function qiye_zdsx_file_create_qiye_page($qiye_id){
	 drupal_set_title('企业重大事项');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('qiye_zdsx_file_create_qiye_form',$qiye_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function qiye_zdsx_file_create_qiye_form($form, &$form_state,$qiye_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $qiye_id);
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '企业重大事项上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function qiye_zdsx_file_create_qiye_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('qiye_zdsx_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'beitouqiye_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'qiye_zdsx_file/qiyelist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//传入投资章程id
function qiye_zdsx_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;

  $query = "SELECT id, name, url,timestamp,remark,user_id,upload_name,beitouqiye_id FROM " .
           "{qiye_zdsx_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;
  if(user_access('upload edit files')){
 		$page_content .= l('编辑','qiye_zdsx_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
  }
  foreach($queryResult as $links){
  	  $page_content .= l('返回列表','qiye_zdsx_file/qiyelist/'.$links->beitouqiye_id) . '<br />'. '<br />';
   	  $ifempty = FALSE;
	  $page_content .= '<h5>企业重大事项材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该企业重大事项材料信息.";
  }
  return $page_content;
}

//企业重大事项编辑
function qiye_zdsx_file_edit_page($perid) {
  $page_content = '';

  $page_content .= l('浏览','qiye_zdsx_file/view/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 	
  drupal_set_title('企业重大事项管理');
	 
  $query = "SELECT id,name, url,beitouqiye_id FROM " .
           "{qiye_zdsx_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('qiye_zdsx_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
 	     $page_content .= l('返回列表','qiye_zdsx_file/qiyelist/'.$links->beitouqiye_id) . '<br />'. '<br />';
	 	 $page_content .= '<h5>已上传企业重大事项:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('qiye_zdsx_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function qiye_zdsx_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{qiye_zdsx_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['qiye_zdsx_file_edit_form']['name'])?$_SESSION['qiye_zdsx_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['qiye_zdsx_file_edit_form']['upload_name'])?$_SESSION['qiye_zdsx_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交企业重大事项材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['qiye_zdsx_file_edit_form']['remark'])?$_SESSION['qiye_zdsx_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('qiye_zdsx_file_edit_form_delete'),
	  );
		  
  return $form;
}

function qiye_zdsx_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('qiye_zdsx_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'qiye_zdsx_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('qiye_zdsx_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'qiye_zdsx_file/view/'.$values['bid'];
	}
}

function qiye_zdsx_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['qiye_zdsx_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['qiye_zdsx_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'qiye_zdsx_file/delete/'.$values['bid'];
}

//企业重大事项删除
function qiye_zdsx_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除企业重大事项内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('qiye_zdsx_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function qiye_zdsx_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('qiye_zdsx_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function qiye_zdsx_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['qiye_zdsx_file_edit_form'])){
		  	$form_state['redirect'] = 'qiye_zdsx_file/list';
	  }else{
		  $values = $_SESSION['qiye_zdsx_file_edit_form'];
		  unset($_SESSION['qiye_zdsx_file_edit_form']);
		  $form_state['redirect'] = 'qiye_zdsx_file/edit/'.$values['bid'];
	  }
}

function qiye_zdsx_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['qiye_zdsx_file_edit_form'])){
		  $form_state['redirect'] = 'qiye_zdsx_file/fundlist';
	  }else{
	  	  
		  $values = $_SESSION['qiye_zdsx_file_edit_form'];
		  unset($_SESSION['qiye_zdsx_file_edit_form']);
		  $query = "SELECT beitouqiye_id FROM " .
           "{qiye_sjbg_file_info} where id = ?";
		  $queryResult = db_query($query, array($values['bid']));
		  $qiyeid ='';
		  foreach ($queryResult as $links ) {
				  $qiyeid = $links->beitouqiye_id;
		  }
          $file = file_load($values['file_managed_id']);
		  if($file!=NULL){
			 file_delete($file);
		  }
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('qiye_zdsx_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'qiye_zdsx_file/qiyelist/'.$qiyeid;

	  }

}

//企业重大事项列表
function qiye_zdsx_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .= l('基金选择列表', 'qiye_zdsx_file/fundlist'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传企业重大事项', 'qiye_zdsx_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('qiye_zdsx_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('beitouqiye_id',0,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'qiye_zdsx_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','qiye_zdsx_file/edit/'. $node->id),
        l('删除','qiye_zdsx_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//传入企业id
function qiye_zdsx_file_qiyelist_perpage($qiye_id) {
  // content variable that will be returned for display
  $html = '';
  $query = "SELECT  fund_id ,company_name FROM " .
           "{beitouqiye_info} where id = ?";
  $queryResult = db_query($query, array($qiye_id));
  $company_name = '';
  foreach ($queryResult as $result) {
        $html .= l('企业选择列表', 'qiye_zdsx_file/qiye/'.$result->fund_id). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	    $company_name = $result->company_name;
  }
  $html .=  l('上传企业重大事项', 'qiye_zdsx_file/create/qiyeid/'.$qiye_id).'<br><br>';
  $html .=  $company_name;
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('qiye_zdsx_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('beitouqiye_id',$qiye_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'qiye_zdsx_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','qiye_zdsx_file/edit/'. $node->id),
        l('删除','qiye_zdsx_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//企业选择入口
function qiye_zdsx_file_qiyelist_page($fund_id) {
  $html = '';	
  $html .= l('返回基金列表','qiye_zdsx_file/fundlist/') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
  $html .= l('添加被投企业信息','beitouqiye/create/'.$fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .= l('导出','beitouqiye/exportcsv/'.$fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  'custom_css' => drupal_get_path('module','my_module').'/css/print.css',
  );

  $html .= area_print_form($options). '<br />'. '<br />';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  $html .= '<div id="printable_div">';
  $round_num = 1;
  $header = array(
      array('data' => '序号'),
      array('data' => '被投企业名称', 'field' => 'company_name'),
      array('data' => '投资时间', 'field' => 'touzi_timestamp'),
      array('data' => '投资额(万元)', 'field' => 'touzi_money'),
      array('data' => '占股比例', 'field' => 'zhangu_percentage'),
      array('data' => '发展阶段', 'field' => 'fazhanjieduan'),
      array('data' => '企业重大事项管理'),
      );
  $query = db_select('beitouqiye_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(20)//20 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'company_name',
      'touzi_timestamp',
      'touzi_money',
      'zhangu_percentage',
      'fazhanjieduan',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  $_serial_num = 1;
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        $_serial_num,
        l($node->company_name, 'beitouqiye/list/'. $node->id),
        format_date($node->touzi_timestamp, 'custom', 'Y-m-d'),
        $node->touzi_money,
        $node->zhangu_percentage,
        $node->fazhanjieduan,
         l('进入', 'qiye_zdsx_file/qiyelist/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有被投企业信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= '</div>';
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  
  return ($html); 
}

//企业重大事项设置基金选择入口
function qiye_zdsx_file_fundlist_page() {
 $html = '';
 
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '企业重大事项设置', 'field' => 'beitouqiye_set'),
      //array('data' => '被投企业资本到位记录列表', 'field' => 'beitouqiye_set'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
          $title = l('企业重大事项设置', 'qiye_zdsx_file/qiye/'.$node->id);
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        $title,
	        //l('资本到位', 'zibendaowei/jilu/ren_fund/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

/////////
//已投企业年审计报告
////////

function qiye_sjbg_file_create_page(){
	 drupal_set_title('企业年审计报告');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('qiye_sjbg_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function qiye_sjbg_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '企业年审计报告上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function qiye_sjbg_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('qiye_sjbg_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'beitouqiye_id' => 0,
			  		     ))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'qiye_sjbg_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}
//传入企业id
function qiye_sjbg_file_create_qiye_page($qiye_id){
	 drupal_set_title('企业年审计报告');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('qiye_sjbg_file_create_qiye_form',$qiye_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function qiye_sjbg_file_create_qiye_form($form, &$form_state,$qiye_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $qiye_id);
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '企业年审计报告上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function qiye_sjbg_file_create_qiye_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('qiye_sjbg_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'beitouqiye_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'qiye_sjbg_file/qiyelist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//传入投资章程id
function qiye_sjbg_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;

  $query = "SELECT id, name, url,timestamp,remark,user_id,upload_name,beitouqiye_id FROM " .
           "{qiye_sjbg_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;
  if(user_access('upload edit files')){
 		$page_content .= l('编辑','qiye_sjbg_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
  }
  foreach($queryResult as $links){
  	  $page_content .= l('返回列表','qiye_sjbg_file/qiyelist/'.$links->beitouqiye_id) . '<br />'. '<br />';
   	  $ifempty = FALSE;
	  $page_content .= '<h5>企业年审计报告材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该企业年审计报告材料信息.";
  }
  return $page_content;
}

//企业年审计报告编辑
function qiye_sjbg_file_edit_page($perid) {
  $page_content = '';

  $page_content .= l('浏览','qiye_sjbg_file/view/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 	
  drupal_set_title('企业年审计报告管理');
	 
  $query = "SELECT id,name, url,beitouqiye_id FROM " .
           "{qiye_sjbg_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('qiye_sjbg_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
 	     $page_content .= l('返回列表','qiye_sjbg_file/qiyelist/'.$links->beitouqiye_id) . '<br />'. '<br />';
	 	 $page_content .= '<h5>已上传企业年审计报告:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('qiye_sjbg_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function qiye_sjbg_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{qiye_sjbg_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['qiye_sjbg_file_edit_form']['name'])?$_SESSION['qiye_sjbg_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['qiye_sjbg_file_edit_form']['upload_name'])?$_SESSION['qiye_sjbg_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交企业年审计报告材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['qiye_sjbg_file_edit_form']['remark'])?$_SESSION['qiye_sjbg_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('qiye_sjbg_file_edit_form_delete'),
	  );
		  
  return $form;
}

function qiye_sjbg_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('qiye_sjbg_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'qiye_sjbg_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('qiye_sjbg_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'qiye_sjbg_file/view/'.$values['bid'];
	}
}

function qiye_sjbg_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['qiye_sjbg_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['qiye_sjbg_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'qiye_sjbg_file/delete/'.$values['bid'];
}

//企业年审计报告删除
function qiye_sjbg_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除企业年审计报告内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('qiye_sjbg_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function qiye_sjbg_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('qiye_sjbg_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function qiye_sjbg_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['qiye_sjbg_file_edit_form'])){
		  	$form_state['redirect'] = 'qiye_sjbg_file/list';
	  }else{
		  $values = $_SESSION['qiye_sjbg_file_edit_form'];
		  unset($_SESSION['qiye_sjbg_file_edit_form']);
		  $form_state['redirect'] = 'qiye_sjbg_file/edit/'.$values['bid'];
	  }
}

function qiye_sjbg_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['qiye_sjbg_file_edit_form'])){
		  $form_state['redirect'] = 'qiye_sjbg_file/fundlist';
	  }else{
		  $values = $_SESSION['qiye_sjbg_file_edit_form'];
		  unset($_SESSION['qiye_sjbg_file_edit_form']);
		  $query = "SELECT beitouqiye_id FROM " .
           "{qiye_sjbg_file_info} where id = ?";
		  $queryResult = db_query($query, array($values['bid']));
		  $qiyeid ='';
		  foreach ($queryResult as $links ) {
				  $qiyeid = $links->beitouqiye_id;
		  }
          $file = file_load($values['file_managed_id']);
		  if($file!=NULL){
			 file_delete($file);
		  }
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('qiye_sjbg_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'qiye_sjbg_file/qiyelist/'.$qiyeid;

	  }

}

//企业年审计报告列表
function qiye_sjbg_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .= l('基金选择列表', 'qiye_sjbg_file/fundlist'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传企业年审计报告', 'qiye_sjbg_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('qiye_sjbg_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('beitouqiye_id',0,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'qiye_sjbg_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','qiye_sjbg_file/edit/'. $node->id),
        l('删除','qiye_sjbg_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//传入企业id
function qiye_sjbg_file_qiyelist_perpage($qiye_id) {
  // content variable that will be returned for display
  $html = '';
  $query = "SELECT  fund_id ,company_name FROM " .
           "{beitouqiye_info} where id = ?";
  $queryResult = db_query($query, array($qiye_id));
  $company_name = '';
  foreach ($queryResult as $result) {
        $html .= l('企业选择列表', 'qiye_sjbg_file/qiye/'.$result->fund_id). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	    $company_name = $result->company_name;
  }
  $html .=  l('上传企业年审计报告', 'qiye_sjbg_file/create/qiyeid/'.$qiye_id).'<br><br>';
  $html .=  $company_name;
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('qiye_sjbg_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('beitouqiye_id',$qiye_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'qiye_sjbg_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','qiye_sjbg_file/edit/'. $node->id),
        l('删除','qiye_sjbg_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//企业选择入口
function qiye_sjbg_file_qiyelist_page($fund_id) {
  $html = '';	
  $html .= l('返回基金列表','qiye_sjbg_file/fundlist/') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
  $html .= l('添加被投企业信息','beitouqiye/create/'.$fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .= l('导出','beitouqiye/exportcsv/'.$fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  'custom_css' => drupal_get_path('module','my_module').'/css/print.css',
  );

  $html .= area_print_form($options). '<br />'. '<br />';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  $html .= '<div id="printable_div">';
  $round_num = 1;
  $header = array(
      array('data' => '序号'),
      array('data' => '被投企业名称', 'field' => 'company_name'),
      array('data' => '投资时间', 'field' => 'touzi_timestamp'),
      array('data' => '投资额(万元)', 'field' => 'touzi_money'),
      array('data' => '占股比例', 'field' => 'zhangu_percentage'),
      array('data' => '发展阶段', 'field' => 'fazhanjieduan'),
      array('data' => '企业年审计报告管理'),
      );
  $query = db_select('beitouqiye_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(20)//20 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'company_name',
      'touzi_timestamp',
      'touzi_money',
      'zhangu_percentage',
      'fazhanjieduan',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  $_serial_num = 1;
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        $_serial_num,
        l($node->company_name, 'beitouqiye/list/'. $node->id),
        format_date($node->touzi_timestamp, 'custom', 'Y-m-d'),
        $node->touzi_money,
        $node->zhangu_percentage,
        $node->fazhanjieduan,
         l('进入', 'qiye_sjbg_file/qiyelist/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有被投企业信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= '</div>';
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  
  return ($html); 
}

//企业年审计报告设置基金选择入口
function qiye_sjbg_file_fundlist_page() {
 $html = '';
 
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '企业年审计报告设置', 'field' => 'beitouqiye_set'),
      //array('data' => '被投企业资本到位记录列表', 'field' => 'beitouqiye_set'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
          $title = l('企业年审计报告设置', 'qiye_sjbg_file/qiye/'.$node->id);
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        $title,
	        //l('资本到位', 'zibendaowei/jilu/ren_fund/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}


/////////
//投资标准与限制标准上传
////////

function touzibiaozhun_file_create_page(){
	 drupal_set_title('投资标准与限制标准');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('touzibiaozhun_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function touzibiaozhun_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '投资标准与限制标准上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function touzibiaozhun_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('touzibiaozhun_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => 0,
			  		     ))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'touzibiaozhun_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function touzibiaozhun_file_create_fund_page($fund_id){
	 drupal_set_title('投资标准与限制标准');
	 $html = '';
	 $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
	 $render_array = array(
	   		'#markup' => $html,
     );
	 
     $form = drupal_get_form('touzibiaozhun_file_create_fund_form',$fund_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function touzibiaozhun_file_create_fund_form($form, &$form_state,$fund_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $fund_id);
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '投资标准与限制标准上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function touzibiaozhun_file_create_fund_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('touzibiaozhun_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'touzibiaozhun_file/fundlist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//投资标准与限制标准浏览
function touzibiaozhun_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;
   if(user_access('upload edit files')){
 		$page_content .= l('编辑','touzibiaozhun_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  }
  $page_content .= l('返回列表','touzibiaozhun_file/list') . '<br />'. '<br />';
  $query = "SELECT id, name,url,timestamp,remark,user_id,upload_name FROM " .
           "{touzibiaozhun_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;
 
  foreach($queryResult as $links){
   	  $ifempty = FALSE;
	  $page_content .= '<h5>投资标准与限制标准材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该投资标准与限制标准材料信息.";
  }
  return $page_content;
}

//投资标准与限制标准编辑
function touzibiaozhun_file_edit_page($perid) {
  $page_content = '';
  $page_content .= l('返回列表','touzibiaozhun_file/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $page_content .= l('浏览','touzibiaozhun_file/view/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('投资标准与限制标准管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{touzibiaozhun_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('touzibiaozhun_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已上传投资标准与限制标准:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('touzibiaozhun_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function touzibiaozhun_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{touzibiaozhun_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['touzibiaozhun_file_edit_form']['name'])?$_SESSION['touzibiaozhun_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['touzibiaozhun_file_edit_form']['upload_name'])?$_SESSION['touzibiaozhun_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交投资标准与限制标准材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['touzibiaozhun_file_edit_form']['remark'])?$_SESSION['touzibiaozhun_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('touzibiaozhun_file_edit_form_delete'),
	  );
		  
  return $form;
}

function touzibiaozhun_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('touzibiaozhun_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'touzibiaozhun_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('touzibiaozhun_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'touzibiaozhun_file/view/'.$values['bid'];
	}
}

function touzibiaozhun_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['touzibiaozhun_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['touzibiaozhun_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'touzibiaozhun_file/delete/'.$values['bid'];
}

//投资标准与限制标准删除
function touzibiaozhun_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除投资标准与限制标准内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('touzibiaozhun_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function touzibiaozhun_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('touzibiaozhun_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function touzibiaozhun_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['touzibiaozhun_file_edit_form'])){
		  	$form_state['redirect'] = 'touzibiaozhun_file/list';
	  }else{
		  $values = $_SESSION['touzibiaozhun_file_edit_form'];
		  unset($_SESSION['touzibiaozhun_file_edit_form']);
		  $form_state['redirect'] = 'touzibiaozhun_file/edit/'.$values['bid'];
	  }
}

function touzibiaozhun_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['touzibiaozhun_file_edit_form'])){
		  $form_state['redirect'] = 'touzibiaozhun_file/list';
	  }else{
		  $values = $_SESSION['touzibiaozhun_file_edit_form'];
		  unset($_SESSION['touzibiaozhun_file_edit_form']);

          $file = file_load($values['file_managed_id']);
		  if($file!=NULL){
			 file_delete($file);
		  }
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('touzibiaozhun_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'touzibiaozhun_file/fund';

	  }

}

//投资标准与限制标准列表
function touzibiaozhun_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .= l('基金选择列表', 'touzibiaozhun_file/fund'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传投资标准与限制标准', 'touzibiaozhun_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('touzibiaozhun_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',0,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'touzibiaozhun_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','touzibiaozhun_file/edit/'. $node->id),
        l('删除','touzibiaozhun_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//投资标准与限制标准列表
function touzibiaozhun_file_fundlist_perpage($fund_id) {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('返回基金选择列表', 'touzibiaozhun_file/fund'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传投资标准与限制标准', 'touzibiaozhun_file/create/fundid/'.$fund_id).'<br><br>';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('touzibiaozhun_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'touzibiaozhun_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','touzibiaozhun_file/edit/'. $node->id),
        l('删除','touzibiaozhun_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//出资人设置基金选择入口
function touzibiaozhun_file_fundlist_page() {
 $html = '';
 $html .= l('其他投资标准与限制标准列表', 'touzibiaozhun_file/list').'<br><br>';
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '投资标准与限制标准管理'),
      array('data' => '上传投资标准与限制标准'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
          $title = l('投资标准与限制标准管理', 'touzibiaozhun_file/fundlist/'.$node->id);
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        $title,
	        l('新建投资标准与限制标准', 'touzibiaozhun_file/create/fundid/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}


/////////
//会议记录与结果上传
////////

function huiyijilu_file_create_page(){
	 drupal_set_title('会议记录与结果');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('huiyijilu_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function huiyijilu_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '会议记录与结果上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function huiyijilu_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('huiyijilu_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => 0,
			  		     ))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'huiyijilu_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function huiyijilu_file_create_fund_page($fund_id){
	 drupal_set_title('会议记录与结果');
	 $html = '';
	 $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
	 $render_array = array(
	   		'#markup' => $html,
     );
	 
     $form = drupal_get_form('huiyijilu_file_create_fund_form',$fund_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function huiyijilu_file_create_fund_form($form, &$form_state,$fund_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $fund_id);
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '会议记录与结果上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function huiyijilu_file_create_fund_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('huiyijilu_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'huiyijilu_file/fundlist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//会议记录与结果浏览
function huiyijilu_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;
  if(user_access('upload edit files')){
 		$page_content .= l('编辑','huiyijilu_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  }
  $page_content .= l('返回列表','huiyijilu_file/list') . '<br />'. '<br />';
  $query = "SELECT id, name,url,timestamp,remark,user_id,upload_name FROM " .
           "{huiyijilu_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;

  foreach($queryResult as $links){
   	  $ifempty = FALSE;
	  $page_content .= '<h5>会议记录与结果材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该会议记录与结果材料信息.";
  }
  return $page_content;
}

//会议记录与结果编辑
function huiyijilu_file_edit_page($perid) {
  $page_content = '';
  $page_content .= l('返回列表','huiyijilu_file/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $page_content .= l('浏览','huiyijilu_file/view/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('会议记录与结果管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{huiyijilu_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('huiyijilu_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已上传会议记录与结果:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('huiyijilu_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function huiyijilu_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{huiyijilu_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['huiyijilu_file_edit_form']['name'])?$_SESSION['huiyijilu_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['huiyijilu_file_edit_form']['upload_name'])?$_SESSION['huiyijilu_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交会议记录与结果材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['huiyijilu_file_edit_form']['remark'])?$_SESSION['huiyijilu_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('huiyijilu_file_edit_form_delete'),
	  );
		  
  return $form;
}

function huiyijilu_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('huiyijilu_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'huiyijilu_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('huiyijilu_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'huiyijilu_file/view/'.$values['bid'];
	}
}

function huiyijilu_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['huiyijilu_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['huiyijilu_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'huiyijilu_file/delete/'.$values['bid'];
}

//会议记录与结果删除
function huiyijilu_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除会议记录与结果内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('huiyijilu_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function huiyijilu_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('huiyijilu_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function huiyijilu_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['huiyijilu_file_edit_form'])){
		  	$form_state['redirect'] = 'huiyijilu_file/list';
	  }else{
		  $values = $_SESSION['huiyijilu_file_edit_form'];
		  unset($_SESSION['huiyijilu_file_edit_form']);
		  $form_state['redirect'] = 'huiyijilu_file/edit/'.$values['bid'];
	  }
}

function huiyijilu_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['huiyijilu_file_edit_form'])){
		  $form_state['redirect'] = 'huiyijilu_file/list';
	  }else{
		  $values = $_SESSION['huiyijilu_file_edit_form'];
		  unset($_SESSION['huiyijilu_file_edit_form']);

          $file = file_load($values['file_managed_id']);
		  if($file!=NULL){
			 file_delete($file);
		  }
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('huiyijilu_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'huiyijilu_file/fund';

	  }

}

//会议记录与结果列表
function huiyijilu_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .= l('基金选择列表', 'huiyijilu_file/fund'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传会议记录与结果', 'huiyijilu_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('huiyijilu_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',0,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'huiyijilu_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','huiyijilu_file/edit/'. $node->id),
        l('删除','huiyijilu_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//会议记录与结果列表
function huiyijilu_file_fundlist_perpage($fund_id) {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('返回基金选择列表', 'huiyijilu_file/fund'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传会议记录与结果', 'huiyijilu_file/create/fundid/'.$fund_id).'<br><br>';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('huiyijilu_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'huiyijilu_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','huiyijilu_file/edit/'. $node->id),
        l('删除','huiyijilu_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//会议记录与结果基金选择入口
function huiyijilu_file_fundlist_page() {
 $html = '';
 $html .= l('其他会议记录与结果列表', 'huiyijilu_file/list').'<br><br>';
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '会议记录与结果管理'),
      array('data' => '上传会议记录与结果'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
          $title = l('会议记录与结果管理', 'huiyijilu_file/fundlist/'.$node->id);
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        $title,
	        l('新建会议记录与结果', 'huiyijilu_file/create/fundid/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}


/////////
//基金退出方案上传
////////

function fund_exit_scheme_file_create_page(){
	 drupal_set_title('基金退出方案');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('fund_exit_scheme_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function fund_exit_scheme_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '基金退出方案上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function fund_exit_scheme_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('fund_exit_scheme_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => 0,
			  		     ))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'fund_exit_scheme_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function fund_exit_scheme_file_create_fund_page($fund_id){
	 drupal_set_title('基金退出方案');
	 $html = '';
	 $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
	 $render_array = array(
	   		'#markup' => $html,
     );
	 
     $form = drupal_get_form('fund_exit_scheme_file_create_fund_form',$fund_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function fund_exit_scheme_file_create_fund_form($form, &$form_state,$fund_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $fund_id);
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '基金退出方案上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function fund_exit_scheme_file_create_fund_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('fund_exit_scheme_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'fund_exit_scheme_file/fundlist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//基金退出方案浏览
function fund_exit_scheme_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;
  if(user_access('upload edit files')){
 		$page_content .= l('编辑','fund_exit_scheme_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
  }
  $page_content .= l('返回列表','fund_exit_scheme_file/list') . '<br />'. '<br />';
  $query = "SELECT id, name,url,timestamp,remark,user_id,upload_name FROM " .
           "{fund_exit_scheme_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;

  foreach($queryResult as $links){
   	  $ifempty = FALSE;
	  $page_content .= '<h5>基金退出方案材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该基金退出方案材料信息.";
  }
  return $page_content;
}

//基金退出方案编辑
function fund_exit_scheme_file_edit_page($perid) {
  $page_content = '';
  $page_content .= l('返回列表','fund_exit_scheme_file/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $page_content .= l('浏览','fund_exit_scheme_file/view/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('基金退出方案管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{fund_exit_scheme_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('fund_exit_scheme_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已上传基金退出方案:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('fund_exit_scheme_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function fund_exit_scheme_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{fund_exit_scheme_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fund_exit_scheme_file_edit_form']['name'])?$_SESSION['fund_exit_scheme_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fund_exit_scheme_file_edit_form']['upload_name'])?$_SESSION['fund_exit_scheme_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交基金退出方案材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['fund_exit_scheme_file_edit_form']['remark'])?$_SESSION['fund_exit_scheme_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('fund_exit_scheme_file_edit_form_delete'),
	  );
		  
  return $form;
}

function fund_exit_scheme_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('fund_exit_scheme_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'fund_exit_scheme_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('fund_exit_scheme_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'fund_exit_scheme_file/view/'.$values['bid'];
	}
}

function fund_exit_scheme_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['fund_exit_scheme_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['fund_exit_scheme_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'fund_exit_scheme_file/delete/'.$values['bid'];
}

//基金退出方案删除
function fund_exit_scheme_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除基金退出方案内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('fund_exit_scheme_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function fund_exit_scheme_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('fund_exit_scheme_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function fund_exit_scheme_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['fund_exit_scheme_file_edit_form'])){
		  	$form_state['redirect'] = 'fund_exit_scheme_file/list';
	  }else{
		  $values = $_SESSION['fund_exit_scheme_file_edit_form'];
		  unset($_SESSION['fund_exit_scheme_file_edit_form']);
		  $form_state['redirect'] = 'fund_exit_scheme_file/edit/'.$values['bid'];
	  }
}

function fund_exit_scheme_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['fund_exit_scheme_file_edit_form'])){
		  $form_state['redirect'] = 'fund_exit_scheme_file/list';
	  }else{
		  $values = $_SESSION['fund_exit_scheme_file_edit_form'];
		  unset($_SESSION['fund_exit_scheme_file_edit_form']);

          $file = file_load($values['file_managed_id']);
		  if($file!=NULL){
			 file_delete($file);
		  }
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('fund_exit_scheme_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'fund_exit_scheme_file/fund';

	  }

}

//基金退出方案列表
function fund_exit_scheme_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .= l('基金选择列表', 'fund_exit_scheme_file/fund'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传基金退出方案', 'fund_exit_scheme_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('fund_exit_scheme_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',0,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'fund_exit_scheme_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','fund_exit_scheme_file/edit/'. $node->id),
        l('删除','fund_exit_scheme_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//基金退出方案列表
function fund_exit_scheme_file_fundlist_perpage($fund_id) {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('返回基金列表', 'fund_exit_file/fundlist'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传基金退出方案', 'fund_exit_scheme_file/create/fundid/'.$fund_id).'<br><br>';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      );
  $query = db_select('fund_exit_scheme_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'fund_exit_scheme_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//基金退出方案基金选择入口
function fund_exit_scheme_file_fundlist_page() {
 $html = '';
 //$html .= l('返回基金选择列表', 'yunxing_qingkuang/fundlist'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
 //$html .= l('其他基金退出方案列表', 'fund_exit_scheme_file/list').'<br><br>';
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '基金退出方案管理', 'field' => 'bad_set'),
      array('data' => '上传基金退出方案', 'field' => 'bad_upload'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
          $title = l('基金退出方案管理', 'fund_exit_scheme_file/fundlist/'.$node->id);
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        $title,
	        l('新建基金退出方案', 'fund_exit_scheme_file/create/fundid/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

/////////
//基金退出决策上传
////////

function fund_exit_decision_file_create_page(){
	 drupal_set_title('基金退出决策');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('fund_exit_decision_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function fund_exit_decision_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '基金退出决策上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function fund_exit_decision_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('fund_exit_decision_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => 0,
			  		     ))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'fund_exit_decision_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function fund_exit_decision_file_create_fund_page($fund_id){
	 drupal_set_title('基金退出决策');
	 $html = '';
	 $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
	 $render_array = array(
	   		'#markup' => $html,
     );
	 
     $form = drupal_get_form('fund_exit_decision_file_create_fund_form',$fund_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function fund_exit_decision_file_create_fund_form($form, &$form_state,$fund_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $fund_id);
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '基金退出决策上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function fund_exit_decision_file_create_fund_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('fund_exit_decision_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'fund_exit_decision_file/fundlist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//基金退出决策浏览
function fund_exit_decision_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;
  if(user_access('upload edit files')){
 		$page_content .= l('编辑','fund_exit_decision_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  }
  $page_content .= l('返回列表','fund_exit_decision_file/list') . '<br />'. '<br />';
  $query = "SELECT id, name,url,timestamp,remark,user_id,upload_name FROM " .
           "{fund_exit_decision_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;

  foreach($queryResult as $links){
   	  $ifempty = FALSE;
	  $page_content .= '<h5>基金退出决策材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该基金退出决策材料信息.";
  }
  return $page_content;
}

//基金退出决策编辑
function fund_exit_decision_file_edit_page($perid) {
  $page_content = '';
  $page_content .= l('返回列表','fund_exit_decision_file/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $page_content .= l('浏览','fund_exit_decision_file/view/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('基金退出决策管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{fund_exit_decision_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('fund_exit_decision_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已上传基金退出决策:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('fund_exit_decision_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function fund_exit_decision_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{fund_exit_decision_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fund_exit_decision_file_edit_form']['name'])?$_SESSION['fund_exit_decision_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fund_exit_decision_file_edit_form']['upload_name'])?$_SESSION['fund_exit_decision_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交基金退出决策材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['fund_exit_decision_file_edit_form']['remark'])?$_SESSION['fund_exit_decision_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('fund_exit_decision_file_edit_form_delete'),
	  );
		  
  return $form;
}

function fund_exit_decision_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('fund_exit_decision_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'fund_exit_decision_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('fund_exit_decision_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'fund_exit_decision_file/view/'.$values['bid'];
	}
}

function fund_exit_decision_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['fund_exit_decision_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['fund_exit_decision_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'fund_exit_decision_file/delete/'.$values['bid'];
}

//基金退出决策删除
function fund_exit_decision_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除基金退出决策内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('fund_exit_decision_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function fund_exit_decision_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('fund_exit_decision_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function fund_exit_decision_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['fund_exit_decision_file_edit_form'])){
		  	$form_state['redirect'] = 'fund_exit_decision_file/list';
	  }else{
		  $values = $_SESSION['fund_exit_decision_file_edit_form'];
		  unset($_SESSION['fund_exit_decision_file_edit_form']);
		  $form_state['redirect'] = 'fund_exit_decision_file/edit/'.$values['bid'];
	  }
}

function fund_exit_decision_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['fund_exit_decision_file_edit_form'])){
		  $form_state['redirect'] = 'fund_exit_decision_file/list';
	  }else{
		  $values = $_SESSION['fund_exit_decision_file_edit_form'];
		  unset($_SESSION['fund_exit_decision_file_edit_form']);

          $file = file_load($values['file_managed_id']);
		  if($file!=NULL){
			 file_delete($file);
		  }
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('fund_exit_decision_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'fund_exit_decision_file/fund';

	  }

}

//基金退出决策列表
function fund_exit_decision_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .= l('基金选择列表', 'fund_exit_decision_file/fund'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传基金退出决策', 'fund_exit_decision_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('fund_exit_decision_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',0,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'fund_exit_decision_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','fund_exit_decision_file/edit/'. $node->id),
        l('删除','fund_exit_decision_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//基金退出决策列表
function fund_exit_decision_file_fundlist_perpage($fund_id) {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('返回基金列表', 'fund_exit_file/fundlist'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传基金退出决策', 'fund_exit_decision_file/create/fundid/'.$fund_id).'<br><br>';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      );
  $query = db_select('fund_exit_decision_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'fund_exit_decision_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//基金退出决策基金选择入口
function fund_exit_decision_file_fundlist_page() {
 $html = '';
 //$html .= l('返回基金选择列表', 'yunxing_qingkuang/fundlist'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
 //$html .= l('其他基金退出决策列表', 'fund_exit_decision_file/list').'<br><br>';
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '基金退出决策管理', 'field' => 'bad_set'),
      array('data' => '上传基金退出决策', 'field' => 'bad_upload'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
          $title = l('基金退出决策管理', 'fund_exit_decision_file/fundlist/'.$node->id);
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        $title,
	        l('新建基金退出决策', 'fund_exit_decision_file/create/fundid/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

/////////
//基金退出资料上传
////////

function fund_exit_other_file_create_page(){
	 drupal_set_title('基金退出资料');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('fund_exit_other_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function fund_exit_other_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '基金退出资料上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function fund_exit_other_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('fund_exit_other_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => 0,
			  		     ))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'fund_exit_other_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function fund_exit_other_file_create_fund_page($fund_id){
	 drupal_set_title('基金退出资料');
	 $html = '';
	 $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
	 $render_array = array(
	   		'#markup' => $html,
     );
	 
     $form = drupal_get_form('fund_exit_other_file_create_fund_form',$fund_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function fund_exit_other_file_create_fund_form($form, &$form_state,$fund_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $fund_id);
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '基金退出资料上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function fund_exit_other_file_create_fund_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('fund_exit_other_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'fund_exit_other_file/fundlist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//基金退出资料浏览
function fund_exit_other_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;
  if(user_access('upload edit files')){
 	$page_content .= l('编辑','fund_exit_other_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  }
  $page_content .= l('返回列表','fund_exit_other_file/list') . '<br />'. '<br />';
  $query = "SELECT id, name,url,timestamp,remark,user_id,upload_name FROM " .
           "{fund_exit_other_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;

  foreach($queryResult as $links){
   	  $ifempty = FALSE;
	  $page_content .= '<h5>基金退出资料材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该基金退出资料材料信息.";
  }
  return $page_content;
}

//基金退出资料编辑
function fund_exit_other_file_edit_page($perid) {
  $page_content = '';
  $page_content .= l('返回列表','fund_exit_other_file/list'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $page_content .= l('浏览','fund_exit_other_file/view/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('基金退出资料管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{fund_exit_other_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('fund_exit_other_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已上传基金退出资料:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('fund_exit_other_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function fund_exit_other_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{fund_exit_other_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fund_exit_other_file_edit_form']['name'])?$_SESSION['fund_exit_other_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['fund_exit_other_file_edit_form']['upload_name'])?$_SESSION['fund_exit_other_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交基金退出资料材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['fund_exit_other_file_edit_form']['remark'])?$_SESSION['fund_exit_other_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('fund_exit_other_file_edit_form_delete'),
	  );
		  
  return $form;
}

function fund_exit_other_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('fund_exit_other_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'fund_exit_other_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('fund_exit_other_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'fund_exit_other_file/view/'.$values['bid'];
	}
}

function fund_exit_other_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['fund_exit_other_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['fund_exit_other_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'fund_exit_other_file/delete/'.$values['bid'];
}

//基金退出资料删除
function fund_exit_other_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除基金退出资料内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('fund_exit_other_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function fund_exit_other_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('fund_exit_other_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function fund_exit_other_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['fund_exit_other_file_edit_form'])){
		  	$form_state['redirect'] = 'fund_exit_other_file/list';
	  }else{
		  $values = $_SESSION['fund_exit_other_file_edit_form'];
		  unset($_SESSION['fund_exit_other_file_edit_form']);
		  $form_state['redirect'] = 'fund_exit_other_file/edit/'.$values['bid'];
	  }
}

function fund_exit_other_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['fund_exit_other_file_edit_form'])){
		  $form_state['redirect'] = 'fund_exit_other_file/list';
	  }else{
		  $values = $_SESSION['fund_exit_other_file_edit_form'];
		  unset($_SESSION['fund_exit_other_file_edit_form']);

          $file = file_load($values['file_managed_id']);
		  if($file!=NULL){
			 file_delete($file);
		  }
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('fund_exit_other_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'fund_exit_other_file/fund';

	  }

}

//基金退出资料列表
function fund_exit_other_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .= l('基金选择列表', 'fund_exit_other_file/fund'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传基金退出资料', 'fund_exit_other_file/create').'<br><br>';
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('fund_exit_other_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',0,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'fund_exit_other_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','fund_exit_other_file/edit/'. $node->id),
        l('删除','fund_exit_other_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//基金退出资料列表
function fund_exit_other_file_fundlist_perpage($fund_id) {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('返回基金列表', 'fund_exit_file/fundlist'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传基金退出资料', 'fund_exit_other_file/create/fundid/'.$fund_id).'<br><br>';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      );
  $query = db_select('fund_exit_other_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'fund_exit_other_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//基金退出资料基金选择入口
function fund_exit_other_file_fundlist_page() {
 $html = '';
 //$html .= l('返回基金选择列表', 'yunxing_qingkuang/fundlist'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
 //$html .= l('其他基金退出资料列表', 'fund_exit_other_file/list').'<br><br>';
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '基金退出资料管理', 'field' => 'bad_set'),
      array('data' => '上传基金退出资料', 'field' => 'bad_upload'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
          $title = l('基金退出资料管理', 'fund_exit_other_file/fundlist/'.$node->id);
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        $title,
	        l('新建基金退出资料', 'fund_exit_other_file/create/fundid/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//基金退出基金选择入口
function fund_exit_file_fundlist_page() {
 $html = '';
 //$html .= l('返回基金选择列表', 'fund_exit_file/fundlist').'<br><br>';
// $html .= l('其他基金退出资料列表', 'fund_exit_other_file/list').'<br><br>';
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '基金退出方案管理', 'field' => 'schema_upload'),
      array('data' => '基金退出决策管理', 'field' => 'decision_upload'),
      array('data' => '基金退出资料管理', 'field' => 'other_upload'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        l('方案管理', 'fund_exit_scheme_file/fundlist/'.$node->id),
	        l('决策管理', 'fund_exit_decision_file/fundlist/'.$node->id),
	        l('资料管理', 'fund_exit_other_file/fundlist/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}


//子基金信息披露
function jijinxinxipilu_fundlist_page() {
 $html = '';
 if(user_access( 'manage fund file')){
 		global $user;
		$query = "SELECT fund_id FROM {fund_basic_information} WHERE user_id = ?";
		$query_result = db_query($query,array($user->uid));
		$result_values = '';
		$fund_id = "";
		foreach ($query_result as $result_values ) {
			$fund_id = $result_values->fund_id;
		}
		 $header = array(
      array('data' => '基金名称', 'field' => 'registered_name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'contact'),
      array('data' => '季度年度报告', 'field' => 'info_set'),
      array('data' => '重大事项报告', 'field' => 'file_set'), 
      array('data' => '不良信息记录', 'field' => 'file_set'),      
      );
  $query = db_select('fund_basic_information', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'registered_name',
      'contact',
      ))
      ->condition('id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
		  $rows[] = array(
	      'data' => array(
	        $node->registered_name,
	        $node->contact,
	        l('季度年度报告', 'jiduniandu_file/fundlist/'.$node->id),
	        l('重大事项报告', 'zhongdashixiang_file/fundlist/'.$node->id),
	        l('不良信息记录', 'yunxing_file/fundlist/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
 }

 $header = array(
      array('data' => '基金名称', 'field' => 'registered_name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '季度年度报告', 'field' => 'info_set'),
      array('data' => '重大事项报告', 'field' => 'file_set'), 
      array('data' => '不良信息记录', 'field' => 'file_set'),      
      );
 $query = db_select('fund_basic_information', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'registered_name',
      'contact',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
		  $rows[] = array(
	      'data' => array(
	        $node->registered_name,
	        $node->contact,
	        l('季度年度报告', 'jiduniandu_file/fundlist/'.$node->id),
	        l('重大事项报告', 'zhongdashixiang_file/fundlist/'.$node->id),
	        l('不良信息记录', 'yunxing_file/fundlist/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

/////////////////////////////////////
/////使用中
////////////////////////////////////

/////////
//重大事项报告上传
////////

function zhongdashixiang_file_create_page(){
	 drupal_set_title('重大事项报告');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('zhongdashixiang_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function zhongdashixiang_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '重大事项报告上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function zhongdashixiang_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	$fund_id = 0;
	$query = "SELECT id, fund_id FROM " .
           "{fund_basic_information} where user_id = ?";
	 $queryResult = db_query($query, array($user->uid));
	 foreach($queryResult as $result){
	  	$fund_id = $result->fund_id;
	 }
	
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
			    
				$last_id = db_insert('zhongdashixiang_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => $fund_id,
			  		     ))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'zhongdashixiang_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function zhongdashixiang_file_create_fund_page($fund_id){
	 drupal_set_title('重大事项报告');
	 $html = '';
	 $query = "SELECT id, registered_name FROM " .
           "{fund_basic_information} where id = ?";
	 $queryResult = db_query($query, array($fund_id));
	 foreach($queryResult as $result){
	  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->registered_name.'<br><br>';
	 }
	 $render_array = array(
	   		'#markup' => $html,
     );
	 
     $form = drupal_get_form('zhongdashixiang_file_create_fund_form',$fund_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function zhongdashixiang_file_create_fund_form($form, &$form_state,$fund_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $fund_id);
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '重大事项报告上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function zhongdashixiang_file_create_fund_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('zhongdashixiang_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'zhongdashixiang_file/fundlist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//重大事项报告浏览
function zhongdashixiang_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;

  $query = "SELECT id, name,url,timestamp,remark,user_id,upload_name ,fund_id FROM " .
           "{zhongdashixiang_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;
  if(user_access('manage fund file')){
 		$page_content .= l('编辑','zhongdashixiang_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  }
  foreach($queryResult as $links){
   	  $ifempty = FALSE;
	  $page_content .= l('返回列表','zhongdashixiang_file/fundlist/') . '<br />'. '<br />';
	  $page_content .= '<h5>重大事项报告材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该重大事项报告材料信息.";
  }
  return $page_content;
}

//重大事项报告编辑
function zhongdashixiang_file_edit_page($perid) {
  $page_content = '';
  $page_content .= l('返回列表','zhongdashixiang_file/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $page_content .= l('浏览','zhongdashixiang_file/view/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('重大事项报告管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{zhongdashixiang_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('zhongdashixiang_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已上传重大事项报告:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('zhongdashixiang_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function zhongdashixiang_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{zhongdashixiang_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['zhongdashixiang_file_edit_form']['name'])?$_SESSION['zhongdashixiang_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['zhongdashixiang_file_edit_form']['upload_name'])?$_SESSION['zhongdashixiang_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交重大事项报告材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['zhongdashixiang_file_edit_form']['remark'])?$_SESSION['zhongdashixiang_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('zhongdashixiang_file_edit_form_delete'),
	  );
		  
  return $form;
}

function zhongdashixiang_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('zhongdashixiang_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'zhongdashixiang_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('zhongdashixiang_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'zhongdashixiang_file/view/'.$values['bid'];
	}
}

function zhongdashixiang_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['zhongdashixiang_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['zhongdashixiang_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'zhongdashixiang_file/delete/'.$values['bid'];
}

//重大事项报告删除
function zhongdashixiang_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除重大事项报告内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('zhongdashixiang_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function zhongdashixiang_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('zhongdashixiang_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function zhongdashixiang_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['zhongdashixiang_file_edit_form'])){
		  	$form_state['redirect'] = 'zhongdashixiang_file/list';
	  }else{
		  $values = $_SESSION['zhongdashixiang_file_edit_form'];
		  unset($_SESSION['zhongdashixiang_file_edit_form']);
		  $form_state['redirect'] = 'zhongdashixiang_file/edit/'.$values['bid'];
	  }
}

function zhongdashixiang_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['zhongdashixiang_file_edit_form'])){
		  $form_state['redirect'] = 'zhongdashixiang_file/list';
	  }else{
		  $values = $_SESSION['zhongdashixiang_file_edit_form'];
		  unset($_SESSION['zhongdashixiang_file_edit_form']);

          $file = file_load($values['file_managed_id']);
		  if($file!=NULL){
			 file_delete($file);
		  }
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('zhongdashixiang_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'zhongdashixiang_file/fundlist';

	  }

}

//重大事项报告列表
function zhongdashixiang_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('上传重大事项报告', 'zhongdashixiang_file/create').'<br><br>';
  global $user; 
	$fund_id = 0;
	$query = "SELECT id, fund_id FROM " .
           "{fund_basic_information} where user_id = ?";
	 $queryResult = db_query($query, array($user->uid));
	 foreach($queryResult as $result){
	  	$fund_id = $result->fund_id;
	 }
	 
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('zhongdashixiang_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'zhongdashixiang_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','zhongdashixiang_file/edit/'. $node->id),
        l('删除','zhongdashixiang_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//重大事项报告列表
function zhongdashixiang_file_fundlist_perpage($fund_id) {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('返回基金选择列表', 'zhongdashixiang_file/fundlist').'<br><br>';
  //$html .=  l('上传重大事项报告', 'zhongdashixiang_file/create/fundid/'.$fund_id).'<br><br>';
  $query = "SELECT id, registered_name FROM " .
           "{fund_basic_information} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->registered_name.'<br><br>';
  }
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '浏览', 'field' => 'view'),
      //array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('zhongdashixiang_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'zhongdashixiang_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('浏览','zhongdashixiang_file/view/'. $node->id),
        //l('删除','zhongdashixiang_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//重大事项基金选择入口
function zhongdashixiang_file_fundlist_page() {
 if(user_access("manage fund file")){
 	drupal_goto('zhongdashixiang_file/list');
 }
 $html = '';
 $header = array(
      array('data' => '基金名称', 'field' => 'registered_name', 'sort' => 'desc'),
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '查看', 'field' => 'shixiang_set'),
      //array('data' => '上传重大事项备案', 'field' => 'shixiang_upload'),
      );
  $query = db_select('fund_basic_information', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'registered_name',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
  	 $query_xiangmu = db_select('zhongdashixiang_file_info', 'n')
	      ->fields ('n', array (
	      'id',
	      'name',
      	  'url',
	      ))
		  ->condition('fund_id',$node->id,'=');  
	  $results_xiangmu = $query_xiangmu
	      ->execute();
	  foreach ($results_xiangmu as $xiangmu) {
		  $rows[] = array(
	      'data' => array(
	        l($node->registered_name, 'zhongdashixiang_file/fundlist/'. $node->id),
	        $xiangmu->name,
	        l('查看', 'zhongdashixiang_file/view/'.$xiangmu->id),
	      )
	      );
	  }
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

/////////
//季度年度报告上传
////////

function jiduniandu_file_create_page(){
	 drupal_set_title('季度年度报告');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('jiduniandu_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function jiduniandu_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '季度年度报告上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function jiduniandu_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	$fund_id = 0;
	$query = "SELECT id, fund_id FROM " .
           "{fund_basic_information} where user_id = ?";
	 $queryResult = db_query($query, array($user->uid));
	 foreach($queryResult as $result){
	  	$fund_id = $result->fund_id;
	 }
	
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
			    
				$last_id = db_insert('jiduniandu_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => $fund_id,
			  		     ))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'jiduniandu_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function jiduniandu_file_create_fund_page($fund_id){
	 drupal_set_title('季度年度报告');
	 $html = '';
	 $query = "SELECT id, registered_name FROM " .
           "{fund_basic_information} where id = ?";
	 $queryResult = db_query($query, array($fund_id));
	 foreach($queryResult as $result){
	  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->registered_name.'<br><br>';
	 }
	 $render_array = array(
	   		'#markup' => $html,
     );
	 
     $form = drupal_get_form('jiduniandu_file_create_fund_form',$fund_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function jiduniandu_file_create_fund_form($form, &$form_state,$fund_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $fund_id);
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '季度年度报告上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function jiduniandu_file_create_fund_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('jiduniandu_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'jiduniandu_file/fundlist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function jiduniandu_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;

  $query = "SELECT id, name,url,timestamp,remark,user_id,upload_name ,fund_id FROM " .
           "{jiduniandu_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;
  if(user_access('manage fund file')){
 		$page_content .= l('编辑','jiduniandu_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  }
  foreach($queryResult as $links){
   	  $ifempty = FALSE;
	  $page_content .= l('返回列表','jiduniandu_file/fundlist/') . '<br />'. '<br />';
	  $page_content .= '<h5>季度年度报告材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该季度年度报告材料信息.";
  }
  return $page_content;
}

function jiduniandu_file_edit_page($perid) {
  $page_content = '';
  $page_content .= l('返回列表','jiduniandu_file/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $page_content .= l('浏览','jiduniandu_file/view/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('季度年度报告管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{jiduniandu_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('jiduniandu_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已上传季度年度报告:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('jiduniandu_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function jiduniandu_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{jiduniandu_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['jiduniandu_file_edit_form']['name'])?$_SESSION['jiduniandu_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['jiduniandu_file_edit_form']['upload_name'])?$_SESSION['jiduniandu_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交季度年度报告材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['jiduniandu_file_edit_form']['remark'])?$_SESSION['jiduniandu_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('jiduniandu_file_edit_form_delete'),
	  );
		  
  return $form;
}

function jiduniandu_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('jiduniandu_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'jiduniandu_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('jiduniandu_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'jiduniandu_file/view/'.$values['bid'];
	}
}

function jiduniandu_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['jiduniandu_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['jiduniandu_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'jiduniandu_file/delete/'.$values['bid'];
}

function jiduniandu_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除季度年度报告内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('jiduniandu_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function jiduniandu_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('jiduniandu_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function jiduniandu_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['jiduniandu_file_edit_form'])){
		  	$form_state['redirect'] = 'jiduniandu_file/list';
	  }else{
		  $values = $_SESSION['jiduniandu_file_edit_form'];
		  unset($_SESSION['jiduniandu_file_edit_form']);
		  $form_state['redirect'] = 'jiduniandu_file/edit/'.$values['bid'];
	  }
}

function jiduniandu_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['jiduniandu_file_edit_form'])){
		  $form_state['redirect'] = 'jiduniandu_file/list';
	  }else{
		  $values = $_SESSION['jiduniandu_file_edit_form'];
		  unset($_SESSION['jiduniandu_file_edit_form']);

          $file = file_load($values['file_managed_id']);
		  if($file!=NULL){
			 file_delete($file);
		  }
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('jiduniandu_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'jiduniandu_file/fundlist';

	  }

}

function jiduniandu_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('上传季度年度报告', 'jiduniandu_file/create').'<br><br>';
  global $user; 
	$fund_id = 0;
	$query = "SELECT id, fund_id FROM " .
           "{fund_basic_information} where user_id = ?";
	 $queryResult = db_query($query, array($user->uid));
	 foreach($queryResult as $result){
	  	$fund_id = $result->fund_id;
	 }
	 
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('jiduniandu_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'jiduniandu_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','jiduniandu_file/edit/'. $node->id),
        l('删除','jiduniandu_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function jiduniandu_file_fundlist_perpage($fund_id) {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('返回基金选择列表', 'jiduniandu_file/fundlist').'<br><br>';
  //$html .=  l('上传季度年度报告', 'jiduniandu_file/create/fundid/'.$fund_id).'<br><br>';
  $query = "SELECT id, registered_name FROM " .
           "{fund_basic_information} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->registered_name.'<br><br>';
  }
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('jiduniandu_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'jiduniandu_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','jiduniandu_file/edit/'. $node->id),
        l('删除','jiduniandu_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function jiduniandu_file_fundlist_page() {
 if(user_access("manage fund file")){
 	drupal_goto('jiduniandu_file/list');
 }
 $html = '';
 $header = array(
     array('data' => '基金名称', 'field' => 'registered_name', 'sort' => 'desc'),
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '查看', 'field' => 'shixiang_set'),
      //array('data' => '上传季度年度备案', 'field' => 'shixiang_upload'),
      );
  $query = db_select('fund_basic_information', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'registered_name',
      'contact',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
		  $query_xiangmu = db_select('jiduniandu_file_info', 'n')
	      ->fields ('n', array (
	      'id',
	      'name',
      	  'url',
	      ))
		  ->condition('fund_id',$node->id,'=');  
	  $results_xiangmu = $query_xiangmu
	      ->execute();
	  foreach ($results_xiangmu as $xiangmu) {
		  $rows[] = array(
	      'data' => array(
	        l($node->registered_name, 'jiduniandu_file/fundlist/'. $node->id),
	        $xiangmu->name,
	        l('查看', 'jiduniandu_file/view/'.$xiangmu->id),
	      )
	      );
	  }
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

/////////
//运行报告上传
////////

function yunxing_file_create_page(){
	 drupal_set_title('运行报告');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('yunxing_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function yunxing_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '运行报告上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function yunxing_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	$fund_id = 0;
	$query = "SELECT id, fund_id FROM " .
           "{fund_basic_information} where user_id = ?";
	 $queryResult = db_query($query, array($user->uid));
	 foreach($queryResult as $result){
	  	$fund_id = $result->fund_id;
	 }
	
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
			    
				$last_id = db_insert('yunxing_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => $fund_id,
			  		     ))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'yunxing_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function yunxing_file_create_fund_page($fund_id){
	 drupal_set_title('运行报告');
	 $html = '';
	 $query = "SELECT id, registered_name FROM " .
           "{fund_basic_information} where id = ?";
	 $queryResult = db_query($query, array($fund_id));
	 foreach($queryResult as $result){
	  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->registered_name.'<br><br>';
	 }
	 $render_array = array(
	   		'#markup' => $html,
     );
	 
     $form = drupal_get_form('yunxing_file_create_fund_form',$fund_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function yunxing_file_create_fund_form($form, &$form_state,$fund_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $fund_id);
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '运行报告上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function yunxing_file_create_fund_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('yunxing_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'yunxing_file/fundlist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function yunxing_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;

  $query = "SELECT id, name,url,timestamp,remark,user_id,upload_name ,fund_id FROM " .
           "{yunxing_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;
  if(user_access('manage fund file')){
 		$page_content .= l('编辑','yunxing_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  }
  foreach($queryResult as $links){
   	  $ifempty = FALSE;
	  $page_content .= l('返回列表','yunxing_file/fundlist/') . '<br />'. '<br />';
	  $page_content .= '<h5>运行报告材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该运行报告材料信息.";
  }
  return $page_content;
}

function yunxing_file_edit_page($perid) {
  $page_content = '';
  $page_content .= l('返回列表','yunxing_file/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $page_content .= l('浏览','yunxing_file/view/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('运行报告管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{yunxing_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('yunxing_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已上传运行报告:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('yunxing_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function yunxing_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{yunxing_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_file_edit_form']['name'])?$_SESSION['yunxing_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['yunxing_file_edit_form']['upload_name'])?$_SESSION['yunxing_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交运行报告材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['yunxing_file_edit_form']['remark'])?$_SESSION['yunxing_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('yunxing_file_edit_form_delete'),
	  );
		  
  return $form;
}

function yunxing_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('yunxing_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'yunxing_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('yunxing_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'yunxing_file/view/'.$values['bid'];
	}
}

function yunxing_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['yunxing_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['yunxing_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'yunxing_file/delete/'.$values['bid'];
}

function yunxing_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除运行报告内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('yunxing_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function yunxing_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('yunxing_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function yunxing_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['yunxing_file_edit_form'])){
		  	$form_state['redirect'] = 'yunxing_file/list';
	  }else{
		  $values = $_SESSION['yunxing_file_edit_form'];
		  unset($_SESSION['yunxing_file_edit_form']);
		  $form_state['redirect'] = 'yunxing_file/edit/'.$values['bid'];
	  }
}

function yunxing_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['yunxing_file_edit_form'])){
		  $form_state['redirect'] = 'yunxing_file/list';
	  }else{
		  $values = $_SESSION['yunxing_file_edit_form'];
		  unset($_SESSION['yunxing_file_edit_form']);

          $file = file_load($values['file_managed_id']);
		  if($file!=NULL){
			 file_delete($file);
		  }
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('yunxing_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'yunxing_file/fundlist';

	  }

}

function yunxing_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('上传运行报告', 'yunxing_file/create').'<br><br>';
  global $user; 
	$fund_id = 0;
	$query = "SELECT id, fund_id FROM " .
           "{fund_basic_information} where user_id = ?";
	 $queryResult = db_query($query, array($user->uid));
	 foreach($queryResult as $result){
	  	$fund_id = $result->fund_id;
	 }
	 
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('yunxing_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'yunxing_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','yunxing_file/edit/'. $node->id),
        l('删除','yunxing_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function yunxing_file_fundlist_perpage($fund_id) {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('返回基金选择列表', 'yunxing_file/fundlist').'<br><br>';
  //$html .=  l('上传运行报告', 'yunxing_file/create/fundid/'.$fund_id).'<br><br>';
  $query = "SELECT id, registered_name FROM " .
           "{fund_basic_information} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->registered_name.'<br><br>';
  }
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('yunxing_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'yunxing_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','yunxing_file/edit/'. $node->id),
        l('删除','yunxing_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function yunxing_file_fundlist_page() {
 if(user_access("manage fund file")){
 	drupal_goto('yunxing_file/list');
 }
 $html = '';
 $header = array(
      array('data' => '基金名称', 'field' => 'registered_name', 'sort' => 'desc'),
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '查看', 'field' => 'shixiang_set'),
      //array('data' => '上传运行备案', 'field' => 'shixiang_upload'),
      );
  $query = db_select('fund_basic_information', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'registered_name',
      'contact',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
	  $query_xiangmu = db_select('yunxing_file_info', 'n')
	      ->fields ('n', array (
	      'id',
	      'name',
      	  'url',
	      ))
		  ->condition('fund_id',$node->id,'=');  
	  $results_xiangmu = $query_xiangmu
	      ->execute();
	  foreach ($results_xiangmu as $xiangmu) {
		  $rows[] = array(
	      'data' => array(
	        l($node->registered_name, 'yunxing_file/fundlist/'. $node->id),
	        $xiangmu->name,
	        l('查看', 'yunxing_file/view/'.$xiangmu->id),
	      )
	      );
	  }
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}


/////////
//不良信息记录上传
////////

function bad_message_file_create_page(){
	 drupal_set_title('不良信息记录');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('bad_message_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function bad_message_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '不良信息记录上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function bad_message_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	$fund_id = 0;
	$query = "SELECT id, fund_id FROM " .
           "{fund_basic_information} where user_id = ?";
	 $queryResult = db_query($query, array($user->uid));
	 foreach($queryResult as $result){
	  	$fund_id = $result->fund_id;
	 }
	
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
			    
				$last_id = db_insert('bad_message_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => $fund_id,
			  		     ))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'bad_message_file/list';					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function bad_message_file_create_fund_page($fund_id){
	 drupal_set_title('不良信息记录');
	 $html = '';
	 $query = "SELECT id, registered_name FROM " .
           "{fund_basic_information} where id = ?";
	 $queryResult = db_query($query, array($fund_id));
	 foreach($queryResult as $result){
	  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->registered_name.'<br><br>';
	 }
	 $render_array = array(
	   		'#markup' => $html,
     );
	 
     $form = drupal_get_form('bad_message_file_create_fund_form',$fund_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function bad_message_file_create_fund_form($form, &$form_state,$fund_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $fund_id);
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '不良信息记录上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function bad_message_file_create_fund_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('bad_message_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'fund_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'bad_message_file/fundlist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function bad_message_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;

  $query = "SELECT id, name,url,timestamp,remark,user_id,upload_name ,fund_id FROM " .
           "{bad_message_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;
  if(user_access('manage fund file')){
 		$page_content .= l('编辑','bad_message_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  }
  foreach($queryResult as $links){
   	  $ifempty = FALSE;
	  $page_content .= l('返回列表','bad_message_file/fundlist/') . '<br />'. '<br />';
	  $page_content .= '<h5>不良信息记录材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该不良信息记录材料信息.";
  }
  return $page_content;
}

function bad_message_file_edit_page($perid) {
  $page_content = '';
  $page_content .= l('返回列表','bad_message_file/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $page_content .= l('浏览','bad_message_file/view/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('不良信息记录管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{bad_message_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('bad_message_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已上传不良信息记录:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('bad_message_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function bad_message_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{bad_message_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['bad_message_file_edit_form']['name'])?$_SESSION['bad_message_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['bad_message_file_edit_form']['upload_name'])?$_SESSION['bad_message_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交不良信息记录材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['bad_message_file_edit_form']['remark'])?$_SESSION['bad_message_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('bad_message_file_edit_form_delete'),
	  );
		  
  return $form;
}

function bad_message_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('bad_message_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'bad_message_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('bad_message_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'bad_message_file/view/'.$values['bid'];
	}
}

function bad_message_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['bad_message_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['bad_message_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'bad_message_file/delete/'.$values['bid'];
}

function bad_message_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除不良信息记录内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('bad_message_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function bad_message_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('bad_message_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function bad_message_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['bad_message_file_edit_form'])){
		  	$form_state['redirect'] = 'bad_message_file/list';
	  }else{
		  $values = $_SESSION['bad_message_file_edit_form'];
		  unset($_SESSION['bad_message_file_edit_form']);
		  $form_state['redirect'] = 'bad_message_file/edit/'.$values['bid'];
	  }
}

function bad_message_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['bad_message_file_edit_form'])){
		  $form_state['redirect'] = 'bad_message_file/list';
	  }else{
		  $values = $_SESSION['bad_message_file_edit_form'];
		  unset($_SESSION['bad_message_file_edit_form']);

          $file = file_load($values['file_managed_id']);
		  if($file!=NULL){
			 file_delete($file);
		  }
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('bad_message_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'bad_message_file/fundlist';

	  }

}

function bad_message_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('上传不良信息记录', 'bad_message_file/create').'<br><br>';
  global $user; 
	$fund_id = 0;
	$query = "SELECT id, fund_id FROM " .
           "{fund_basic_information} where user_id = ?";
	 $queryResult = db_query($query, array($user->uid));
	 foreach($queryResult as $result){
	  	$fund_id = $result->fund_id;
	 }
	 
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('bad_message_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'bad_message_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','bad_message_file/edit/'. $node->id),
        l('删除','bad_message_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function bad_message_file_fundlist_perpage($fund_id) {
  // content variable that will be returned for display
  $html = '';
  $html .=  l('返回列表', 'bad_message_file/fundlist').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .=  l('上传记录', 'bad_message_file/create/fundid/'.$fund_id).'<br><br>';
  $query = "SELECT id, registered_name FROM " .
           "{fund_basic_information} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->registered_name.'<br><br>';
  }
  $header = array(
      array('data' => '已上传材料', 'field' => 'name'),
      array('data' => '上传人员', 'field' => 'upload_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '编辑', 'field' => 'edit'),
      array('data' => '删除', 'field' => 'deleate'),
      );
  $query = db_select('bad_message_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'upload_name',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'bad_message_file/view/'. $node->id),
        $node->upload_name,
        format_date($node->timestamp, 'custom', 'Y-m-d'),
        $node->remark,
        l('编辑','bad_message_file/edit/'. $node->id),
        l('删除','bad_message_file/delete/'. $node->id),
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function bad_message_file_fundlist_page() {
 if(user_access("manage fund file")){
 	drupal_goto('bad_message_file/list');
 }
 $html = '';
 $header = array(
      array('data' => '基金名称', 'field' => 'registered_name', 'sort' => 'desc'),
      array('data' => '查看', 'field' => 'shixiang_set'),
      );
  $query = db_select('fund_basic_information', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'registered_name',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) { 
		  
		  $rows[] = array(
	      'data' => array(
	        $node->registered_name,
	        l('查看','bad_message_file/fundlist/'. $node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

/////////
//项目退出报告
////////

function qiye_tcbg_file_create_page(){
	 drupal_set_title('项目退出报告');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('qiye_tcbg_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function qiye_tcbg_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '项目退出报告上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function qiye_tcbg_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('qiye_tcbg_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'beitouqiye_id' => 0,
			  		     ))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'qiye_tcbg_file/list';					 	    
				  } else {
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}
//传入企业id
function qiye_tcbg_file_create_qiye_page($qiye_id){
	 drupal_set_title('项目退出报告');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('qiye_tcbg_file_create_qiye_form',$qiye_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function qiye_tcbg_file_create_qiye_form($form, &$form_state,$qiye_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $qiye_id);
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '项目退出报告上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function qiye_tcbg_file_create_qiye_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('qiye_tcbg_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'beitouqiye_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'qiye_tcbg_file/qiyelist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//传入企业id
function qiye_tcbg_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;

  $query = "SELECT id, name, url,timestamp,remark,user_id,upload_name,beitouqiye_id FROM " .
           "{qiye_tcbg_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;
  if(user_access('manage fund file')){
 		$page_content .= l('编辑','qiye_tcbg_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
  }
  foreach($queryResult as $links){
  	  $page_content .= l('返回列表','qiye_tcbg_file/qiyelist/'.$links->beitouqiye_id) . '<br />'. '<br />';
   	  $ifempty = FALSE;
	  $page_content .= '<h5>项目退出报告材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该项目退出报告材料信息.";
  }
  return $page_content;
}

//项目退出报告编辑
function qiye_tcbg_file_edit_page($perid) {
  $page_content = '';

  $page_content .= l('浏览','qiye_tcbg_file/view/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 	
  drupal_set_title('项目退出报告管理');
	 
  $query = "SELECT id,name, url,beitouqiye_id FROM " .
           "{qiye_tcbg_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('qiye_tcbg_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
 	     $page_content .= l('返回列表','qiye_tcbg_file/qiyelist/'.$links->beitouqiye_id) . '<br />'. '<br />';
	 	 $page_content .= '<h5>已上传项目退出报告:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('qiye_tcbg_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function qiye_tcbg_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{qiye_tcbg_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['qiye_tcbg_file_edit_form']['name'])?$_SESSION['qiye_tcbg_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['qiye_tcbg_file_edit_form']['upload_name'])?$_SESSION['qiye_tcbg_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交项目退出报告材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['qiye_tcbg_file_edit_form']['remark'])?$_SESSION['qiye_tcbg_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('qiye_tcbg_file_edit_form_delete'),
	  );
		  
  return $form;
}

function qiye_tcbg_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('qiye_tcbg_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'qiye_tcbg_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('qiye_tcbg_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'qiye_tcbg_file/view/'.$values['bid'];
	}
}

function qiye_tcbg_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['qiye_tcbg_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['qiye_tcbg_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'qiye_tcbg_file/delete/'.$values['bid'];
}

//项目退出报告删除
function qiye_tcbg_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除项目退出报告内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('qiye_tcbg_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function qiye_tcbg_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('qiye_tcbg_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function qiye_tcbg_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['qiye_tcbg_file_edit_form'])){
		  	$form_state['redirect'] = 'qiye_tcbg_file/list';
	  }else{
		  $values = $_SESSION['qiye_tcbg_file_edit_form'];
		  unset($_SESSION['qiye_tcbg_file_edit_form']);
		  $form_state['redirect'] = 'qiye_tcbg_file/edit/'.$values['bid'];
	  }
}

function qiye_tcbg_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['qiye_tcbg_file_edit_form'])){
		  $form_state['redirect'] = 'qiye_tcbg_file/fundlist';
	  }else{
	  	  
		  $values = $_SESSION['qiye_tcbg_file_edit_form'];
		  unset($_SESSION['qiye_tcbg_file_edit_form']);
          $query = "SELECT beitouqiye_id FROM " .
           "{qiye_tcbg_file_info} where id = ?";
		  $queryResult = db_query($query, array($values['bid']));
		  $qiyeid ='';
		  foreach ($queryResult as $links ) {
				  $qiyeid = $links->beitouqiye_id;
		  }
          $file = file_load($values['file_managed_id']);
		  if($file!=NULL){
			 file_delete($file);
		  }
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('qiye_tcbg_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'qiye_tcbg_file/qiyelist/'.$qiyeid;

	  }

}

//项目退出报告列表
function qiye_tcbg_file_list_page() {
  // content variable that will be returned for display
  $html = '';
   $html .= '<br><h3>未退出项目列表</h3><br>';
  $fund_id = 0;
  global $user;
	$query = "SELECT id, fund_id FROM " .
           "{fund_basic_information} where user_id = ?";
	 $queryResult = db_query($query, array($user->uid));
	 foreach($queryResult as $result){
	  	$fund_id = $result->fund_id;
	 }
  $header = array(
  	  array('data' => '项目名称', 'field' => 'xiangmu_set'),
      array('data' => '项目退出报告编辑', 'field' => 'edit'),
       array('data' => '项目退出方案编辑', 'field' => 'edit'),
       array('data' => '退出设置', 'field' => 'beitouqiye_set'),
      );
  $query_xiangmu = db_select('xiangmu_info', 'n')
		      ->fields ('n', array (
		      'id',
		      'company_name',
		      ))
			  ->condition('fund_id',$fund_id,'=')
			  ->condition('state',1,'=')
			  ;  
  $results_xiangmu = $query_xiangmu
		      ->execute();
  $rows = array();
  foreach ($results_xiangmu as $xiangmu) {
		  $rows[] = array(
		      'data' => array(
		        $xiangmu->company_name,
		        l('编辑','qiye_tcbg_file/qiyelist/'. $xiangmu->id),
		        l('编辑','qiye_exit_scheme_file/qiyelist/'. $xiangmu->id),
		        l('设置', 'xiangmu_exit/create/'.$xiangmu->id),
		      )
		      );
  	}
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  $html .= '<br><h3>已退出项目列表</h3><br>';
  $fund_id = 0;
  global $user;
	$query = "SELECT id, fund_id FROM " .
           "{fund_basic_information} where user_id = ?";
	 $queryResult = db_query($query, array($user->uid));
	 foreach($queryResult as $result){
	  	$fund_id = $result->fund_id;
	 }
  $header = array(
  	  array('data' => '项目名称', 'field' => 'xiangmu_set'),
      array('data' => '项目退出报告编辑', 'field' => 'edit'),
       array('data' => '项目退出方案编辑', 'field' => 'edit'),
        array('data' => '退出设置', 'field' => 'beitouqiye_set'),
      );
  $query_xiangmu = db_select('xiangmu_info', 'n')
		      ->fields ('n', array (
		      'id',
		      'company_name',
		      ))
			  ->condition('fund_id',$fund_id,'=')
			  ->condition('state',3,'=')
			  ;  
  $results_xiangmu = $query_xiangmu
		      ->execute();
  $rows = array();
  foreach ($results_xiangmu as $xiangmu) {
		  $rows[] = array(
		      'data' => array(
		        $xiangmu->company_name,
		        l('编辑','qiye_tcbg_file/qiyelist/'. $xiangmu->id),
		        l('编辑','qiye_exit_scheme_file/qiyelist/'. $xiangmu->id),
		        l('设置', 'xiangmu_exit/list/'.$xiangmu->id),
		      )
		      );
  	}
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
	  
  return ($html); 
}

//传入企业id
function qiye_tcbg_file_qiyelist_perpage($qiye_id) {
  // content variable that will be returned for display
  $html = '';
  $query = "SELECT fund_id, company_name FROM " .
           "{xiangmu_info} where id = ?";
  $queryResult = db_query($query, array($qiye_id));
  $company_name = '';
  $fund_id = '';
  foreach ($queryResult as $result) {
        $fund_id = $result->fund_id;
	    $company_name = $result->company_name;
  }
  
  $rows = array();
  if(user_access('manage fund file')){
  	
  	  $html .= l('返回列表','qiye_tcbg_file/list') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
  	  $html .=  l('上传项目退出报告', 'qiye_tcbg_file/create/qiyeid/'.$qiye_id).'<br><br>';
	  $header = array(
	      array('data' => '已上传材料', 'field' => 'name'),
	      array('data' => '上传人员', 'field' => 'upload_name'),
	      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
	      array('data' => '编辑', 'field' => 'edit'),
	      array('data' => '删除', 'field' => 'deleate'),
	      );
	  $query = db_select('qiye_tcbg_file_info', 'n')
	      ->extend('PagerDefault') //Pager Extender
	      ->limit(10)//10 results per page
	      ->extend('TableSort')//Sorting Extender
	      ->orderByHeader($header)//Field to sort on is picked from $header
	      ->fields ('n', array (
	      'id',
	      'name',
	      'url',
	      'timestamp',
	      'user_id',
	      'upload_name',
	      ))
		  ->condition('beitouqiye_id',$qiye_id,'=');
	  $results = $query
	      ->execute();
	
	  foreach ($results as $node) {
	      $rows[] = array(
	      'data' => array(
	        l($node->name, 'qiye_tcbg_file/view/'. $node->id),
	        $node->upload_name,
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        $node->remark,
	        l('编辑','qiye_tcbg_file/edit/'. $node->id),
	        l('删除','qiye_tcbg_file/delete/'. $node->id),
	      )
	      );
	  }
  }
	else{
		  $html .= l('返回列表', 'qiye_tcbg_file/fundlist'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
		  $header = array(
		      array('data' => '已上传材料', 'field' => 'name'),
		      array('data' => '上传人员', 'field' => 'upload_name'),
		      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
		      array('data' => '查看', 'field' => 'edit'),
		      );
		  $query = db_select('qiye_tcbg_file_info', 'n')
		      ->extend('PagerDefault') //Pager Extender
		      ->limit(10)//10 results per page
		      ->extend('TableSort')//Sorting Extender
		      ->orderByHeader($header)//Field to sort on is picked from $header
		      ->fields ('n', array (
		      'id',
		      'name',
		      'url',
		      'timestamp',
		      'user_id',
		      'upload_name',
		      ))
			  ->condition('beitouqiye_id',$qiye_id,'=');
		  $results = $query
		      ->execute();
		
		  foreach ($results as $node) {
		      $rows[] = array(
		      'data' => array(
		        l($node->name, 'qiye_tcbg_file/view/'. $node->id),
		        $node->upload_name,
		        format_date($node->timestamp, 'custom', 'Y-m-d'),
		        l('查看','qiye_tcbg_file/view/'. $node->id),
		      )
		      );
		  }
	}
  
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//选择企业
function qiye_tcbg_file_qiyelist_page($fund_id) {
  $html = '';	
  $html .= l('返回基金列表','qiye_tcbg_file/fundlist/') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
  $html .= l('添加被投企业信息','beitouqiye/create/'.$fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .= l('导出','beitouqiye/exportcsv/'.$fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  'custom_css' => drupal_get_path('module','my_module').'/css/print.css',
  );

  $html .= area_print_form($options). '<br />'. '<br />';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  $html .= '<div id="printable_div">';
  $header = array(
      array('data' => '序号'),
      array('data' => '被投企业名称', 'field' => 'company_name'),
      //array('data' => '投资时间', 'field' => 'touzi_timestamp'),
      array('data' => '投资额(万元)', 'field' => 'touzi_money'),
      array('data' => '占股比例', 'field' => 'zhangu_percentage'),
      array('data' => '发展阶段', 'field' => 'fazhanjieduan'),
      array('data' => '退出方案管理'),
      array('data' => '退出报告管理'),
      array('data' => '退出信息管理（重要）'),
      );
  $query = db_select('beitouqiye_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(20)//20 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'company_name',
      'touzi_timestamp',
      'touzi_money',
      'zhangu_percentage',
      'fazhanjieduan',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows1 = array();
  $rows2 = array();
  $serial_num1 = 1;
  $serial_num2 = 1;
  foreach ($results as $node) {
  	  $query = "SELECT id FROM " .
           "{company_exit_info} where beitouqiye_id = ?";
	  $queryResult = db_query($query, array($node->id));
	  $beitouqiye_id = '';
	  foreach($queryResult as $result){
	  	$beitouqiye_id = $result->id;
	  }
	  if($beitouqiye_id>0){
	  	$rows1[] = array(
	      'data' => array(
	        $serial_num1,
	        l($node->company_name, 'beitouqiye/list/'. $node->id),
	        //format_date($node->touzi_timestamp, 'custom', 'Y-m-d'),
	        $node->touzi_money,
	        $node->zhangu_percentage,
	        $node->fazhanjieduan,
	         l('进入', 'qiye_exit_scheme_file/qiyelist/'. $node->id),
	         l('进入', 'qiye_tcbg_file/qiyelist/'. $node->id),
	         l('查看', 'company_exit/list/'. $beitouqiye_id),
	      )
	      );
		  $serial_num1++;
	  }

	  else{
	  	$rows2[] = array(
	      'data' => array(
	        $serial_num2,
	        l($node->company_name, 'beitouqiye/list/'. $node->id),
	        //format_date($node->touzi_timestamp, 'custom', 'Y-m-d'),
	        $node->touzi_money,
	        $node->zhangu_percentage,
	        $node->fazhanjieduan,
	         l('进入', 'qiye_exit_scheme_file/qiyelist/'. $node->id),
	         l('进入', 'qiye_tcbg_file/qiyelist/'. $node->id),
	         l('填写', 'company_exit/create/'. $node->id),
	      )
	      );
		  $serial_num2++;
	  }     
  }
  $html .= '已退出企业列表<br>';
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows1,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有已退出企业信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  $html .= '未退出企业列表<br>';
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows2,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有未退出企业信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  $html .= '</div>';
  return ($html); 
}

//项目退出报告设置基金选择入口
function qiye_tcbg_file_fundlist_page() {
 $html = '';
 $html .= '<br><h3>未退出项目列表</h3><br>';
 $header = array(
      array('data' => '基金名称', 'field' => 'registered_name', 'sort' => 'desc'),
      array('data' => '项目名称', 'field' => 'xiangmu_set'),
      array('data' => '退出报告管理', 'field' => 'beitouqiye_set'),
      array('data' => '退出方案管理', 'field' => 'beitouqiye_set'),
      array('data' => '退出设置', 'field' => 'beitouqiye_set'),
      );
  $query = db_select('fund_basic_information', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'registered_name',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
  			$query_xiangmu = db_select('xiangmu_info', 'n')
		      ->fields ('n', array (
		      'id',
		      'company_name',
		      ))
			  ->condition('fund_id',$node->id,'=')
			  ->condition('state',1,'=');  
		  $results_xiangmu = $query_xiangmu
		      ->execute();
		  foreach ($results_xiangmu as $xiangmu) {
			  $rows[] = array(
		      'data' => array(
		        $node->registered_name,
		        $xiangmu->company_name,
		        l('查看', 'qiye_tcbg_file/qiyelist/'.$xiangmu->id),
		        l('查看', 'qiye_exit_scheme_file/qiyelist/'.$xiangmu->id),
		        "尚未退出",
		      )
		      );
			}
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有项目信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
	  
 $html .= '<br><h3>已退出项目列表</h3><br>';
 $header = array(
      array('data' => '基金名称', 'field' => 'registered_name', 'sort' => 'desc'),
      array('data' => '项目名称', 'field' => 'xiangmu_set'),
      array('data' => '退出报告管理', 'field' => 'beitouqiye_set'),
      array('data' => '退出方案管理', 'field' => 'beitouqiye_set'),
      array('data' => '退出设置', 'field' => 'beitouqiye_set'),
      );
  $query = db_select('fund_basic_information', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'registered_name',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
  			$query_xiangmu = db_select('xiangmu_info', 'n')
		      ->fields ('n', array (
		      'id',
		      'company_name',
		      ))
			  ->condition('fund_id',$node->id,'=')
			  ->condition('state',3,'=');  
		  $results_xiangmu = $query_xiangmu
		      ->execute();
		  foreach ($results_xiangmu as $xiangmu) {
			  $rows[] = array(
		      'data' => array(
		        $node->registered_name,
		        $xiangmu->company_name,
		        l('查看', 'qiye_tcbg_file/qiyelist/'.$xiangmu->id),
		        l('查看', 'qiye_exit_scheme_file/qiyelist/'.$xiangmu->id),
		        l('查看', 'fund_exit/list/'.$xiangmu->id),
		      )
		      );
			}
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有项目信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}





/////////
//项目退出方案资料
////////

function qiye_exit_scheme_file_create_page(){
	 drupal_set_title('项目退出报告');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('qiye_exit_scheme_file_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function qiye_exit_scheme_file_create_form($form, &$form_state){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '项目退出方案上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function qiye_exit_scheme_file_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('qiye_exit_scheme_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'beitouqiye_id' => 0,
			  		     ))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'qiye_exit_scheme_file/list';					 	    
				  } else {
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}
//传入企业id
function qiye_exit_scheme_file_create_qiye_page($qiye_id){
	 drupal_set_title('项目退出方案');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('qiye_exit_scheme_file_create_qiye_form',$qiye_id);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function qiye_exit_scheme_file_create_qiye_form($form, &$form_state,$qiye_id){
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['bid'] = array('#type' => 'hidden', '#value' => $qiye_id);
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '项目退出方案上传',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['file_name'] = array(
	  '#title' => t('显示文件名：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	 
	 $form['upload_name'] = array(
	  '#title' => t('上传人员：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function qiye_exit_scheme_file_create_qiye_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);			
				$last_id = db_insert('qiye_exit_scheme_file_info')
			  		->fields(array(
			   			 'name' => $values['file_name'],
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'upload_name' => $values['upload_name'],
			   			 'remark' => $values['remark'],
			   			 'user_id' => $user->uid,
			   			 'file_managed_id' => $fid,
			   			 'beitouqiye_id' => $values['bid'],
			  			))->execute();
				  if ($last_id!=NULL) {			
					 $form_state['redirect'] = 'qiye_exit_scheme_file/qiyelist/'.$values['bid'];					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

//传入企业id
function qiye_exit_scheme_file_view_page($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;

  $query = "SELECT id, name, url,timestamp,remark,user_id,upload_name,beitouqiye_id FROM " .
           "{qiye_exit_scheme_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty = TRUE;
  if(user_access('manage fund file')){
 		$page_content .= l('编辑','qiye_exit_scheme_file/edit/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
  }
  foreach($queryResult as $links){
  	  $page_content .= l('返回列表','qiye_exit_scheme_file/qiyelist/'.$links->beitouqiye_id) . '<br />'. '<br />';
   	  $ifempty = FALSE;
	  $page_content .= '<h5>项目退出方案材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	  $page_content .= '<h5>上传人员:</h5>'.$links->upload_name.'<br />'.'<br />';
	  $page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'Y-m-d').'<br />'.'<br />';
	  $page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
  }	
  // More coming....
  if ($ifempty) {
    $page_content = "没有该项目退出方案材料信息.";
  }
  return $page_content;
}

//项目退出方案编辑
function qiye_exit_scheme_file_edit_page($perid) {
  $page_content = '';

  $page_content .= l('浏览','qiye_exit_scheme_file/view/'.$perid) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 	
  drupal_set_title('项目退出方案管理');
	 
  $query = "SELECT id,name, url,beitouqiye_id FROM " .
           "{qiye_exit_scheme_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('qiye_exit_scheme_file_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
 	     $page_content .= l('返回列表','qiye_exit_scheme_file/qiyelist/'.$links->beitouqiye_id) . '<br />'. '<br />';
	 	 $page_content .= '<h5>已上传项目退出方案:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('qiye_exit_scheme_file_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function qiye_exit_scheme_file_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark,user_id,upload_name,file_managed_id FROM " .
           "{qiye_exit_scheme_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $upload_name = '';
  global $user;
 foreach ($queryResult as $links ) {
    $name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
  	$upload_name = $links->upload_name;
	$file_managed_id = $links->file_managed_id;
  }
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['qiye_exit_scheme_file_edit_form']['name'])?$_SESSION['qiye_exit_scheme_file_edit_form']['name']:$name,
	 );
	 
    $form['upload_name'] = array(
	  '#title' => t('上传人员'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['qiye_exit_scheme_file_edit_form']['upload_name'])?$_SESSION['qiye_exit_scheme_file_edit_form']['upload_name']:$upload_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交项目退出方案材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx zip tar.gz 7z'),
		'file_validate_size' => array(20*1024*1024)),
	);

	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['qiye_exit_scheme_file_edit_form']['remark'])?$_SESSION['qiye_exit_scheme_file_edit_form']['remark']:$remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该材料'),
	    '#submit' => array('qiye_exit_scheme_file_edit_form_delete'),
	  );
		  
  return $form;
}

function qiye_exit_scheme_file_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	global $user; 
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx zip tar.gz 7z");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			db_update('qiye_exit_scheme_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'upload_name' => $values['upload_name'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
					
			$form_state['redirect'] = 'qiye_exit_scheme_file/view/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		db_update('qiye_exit_scheme_file_info')
			 ->fields(array(
			   	'name' => $filename,
			   	'timestamp' => $_SERVER['REQUEST_TIME'],
			   	'remark' => $values['remark'],			   	
			   	'upload_name' => $values['upload_name'],
			  ))
			  ->condition('id',$uploadid)
			  ->execute();				
				
	    $form_state['redirect'] = 'qiye_exit_scheme_file/view/'.$values['bid'];
	}
}

function qiye_exit_scheme_file_edit_form_delete($form, &$form_state){
	 $values = NULL;
	 $_SESSION['qiye_exit_scheme_file_edit_form'] = $form_state['values'];
	 $values = $_SESSION['qiye_exit_scheme_file_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'qiye_exit_scheme_file/delete/'.$values['bid'];
}

//项目退出方案删除
function qiye_exit_scheme_file_delete_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后该内容将不可恢复！';
  
  drupal_set_title('删除项目退出方案内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('qiye_exit_scheme_file_delete_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function qiye_exit_scheme_file_delete_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('qiye_exit_scheme_file_delete_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function qiye_exit_scheme_file_delete_form_back($form, &$form_state){
	if(empty($_SESSION['qiye_exit_scheme_file_edit_form'])){
		  	$form_state['redirect'] = 'qiye_exit_scheme_file/list';
	  }else{
		  $values = $_SESSION['qiye_exit_scheme_file_edit_form'];
		  unset($_SESSION['qiye_exit_scheme_file_edit_form']);
		  $form_state['redirect'] = 'qiye_exit_scheme_file/edit/'.$values['bid'];
	  }
}

function qiye_exit_scheme_file_delete_form_submit($form, &$form_state){
 if(empty($_SESSION['qiye_exit_scheme_file_edit_form'])){
		  $form_state['redirect'] = 'qiye_exit_scheme_file/fundlist';
	  }else{
	  	  
		  $values = $_SESSION['qiye_exit_scheme_file_edit_form'];
		  unset($_SESSION['qiye_exit_scheme_file_edit_form']);
          $query = "SELECT beitouqiye_id FROM " .
           "{qiye_exit_scheme_file_info} where id = ?";
		  $queryResult = db_query($query, array($values['bid']));
		  $qiyeid ='';
		  foreach ($queryResult as $links ) {
				  $qiyeid = $links->beitouqiye_id;
		  }
          $file = file_load($values['file_managed_id']);
		  if($file!=NULL){
			 file_delete($file);
		  }
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('qiye_exit_scheme_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'qiye_exit_scheme_file/qiyelist/'.$qiyeid;

	  }

}

//项目退出方案列表
function qiye_exit_scheme_file_list_page() {
  // content variable that will be returned for display
  $html = '';
  $fund_id = 0;
  global $user;
	$query = "SELECT id, fund_id FROM " .
           "{fund_basic_information} where user_id = ?";
	 $queryResult = db_query($query, array($user->uid));
	 foreach($queryResult as $result){
	  	$fund_id = $result->fund_id;
	 }
  $header = array(
  	  array('data' => '项目名称', 'field' => 'xiangmu_set'),
      array('data' => '项目退出方案编辑', 'field' => 'edit'),
      );
  $query_xiangmu = db_select('xiangmu_info', 'n')
		      ->fields ('n', array (
		      'id',
		      'company_name',
		      ))
			  ->condition('fund_id',$fund_id,'=')
			  ->condition('state',1,'=')
			  ;  
  $results_xiangmu = $query_xiangmu
		      ->execute();
  $rows = array();
  foreach ($results_xiangmu as $xiangmu) {
		  $rows[] = array(
		      'data' => array(
		        $xiangmu->company_name,
		        l('编辑','qiye_exit_scheme_file/qiyelist/'. $xiangmu->id),
		      )
		      );
  	}
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//传入企业id
function qiye_exit_scheme_file_qiyelist_perpage($qiye_id) {
  // content variable that will be returned for display
  $html = '';
  $query = "SELECT fund_id, company_name FROM " .
           "{xiangmu_info} where id = ?";
  $queryResult = db_query($query, array($qiye_id));
  $company_name = '';
  $fund_id = '';
  foreach ($queryResult as $result) {
        $fund_id = $result->fund_id;
	    $company_name = $result->company_name;
  }
  
  $rows = array();
  if(user_access('manage fund file')){
  	
  	  $html .= l('返回列表','qiye_exit_scheme_file/list') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
  	  $html .=  l('上传项目退出方案', 'qiye_exit_scheme_file/create/qiyeid/'.$qiye_id).'<br><br>';
	  $header = array(
	      array('data' => '已上传材料', 'field' => 'name'),
	      array('data' => '上传人员', 'field' => 'upload_name'),
	      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
	      array('data' => '编辑', 'field' => 'edit'),
	      array('data' => '删除', 'field' => 'deleate'),
	      );
	  $query = db_select('qiye_exit_scheme_file_info', 'n')
	      ->extend('PagerDefault') //Pager Extender
	      ->limit(10)//10 results per page
	      ->extend('TableSort')//Sorting Extender
	      ->orderByHeader($header)//Field to sort on is picked from $header
	      ->fields ('n', array (
	      'id',
	      'name',
	      'url',
	      'timestamp',
	      'user_id',
	      'upload_name',
	      ))
		  ->condition('beitouqiye_id',$qiye_id,'=');
	  $results = $query
	      ->execute();
	
	  foreach ($results as $node) {
	      $rows[] = array(
	      'data' => array(
	        l($node->name, 'qiye_exit_scheme_file/view/'. $node->id),
	        $node->upload_name,
	        format_date($node->timestamp, 'custom', 'Y-m-d'),
	        $node->remark,
	        l('编辑','qiye_exit_scheme_file/edit/'. $node->id),
	        l('删除','qiye_exit_scheme_file/delete/'. $node->id),
	      )
	      );
	  }
  }
	else{
		  $html .= l('返回列表', 'qiye_exit_scheme_file/fundlist'). '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
		  $header = array(
		      array('data' => '已上传材料', 'field' => 'name'),
		      array('data' => '上传人员', 'field' => 'upload_name'),
		      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
		      array('data' => '查看', 'field' => 'edit'),
		      );
		  $query = db_select('qiye_exit_scheme_file_info', 'n')
		      ->extend('PagerDefault') //Pager Extender
		      ->limit(10)//10 results per page
		      ->extend('TableSort')//Sorting Extender
		      ->orderByHeader($header)//Field to sort on is picked from $header
		      ->fields ('n', array (
		      'id',
		      'name',
		      'url',
		      'timestamp',
		      'user_id',
		      'upload_name',
		      ))
			  ->condition('beitouqiye_id',$qiye_id,'=');
		  $results = $query
		      ->execute();
		
		  foreach ($results as $node) {
		      $rows[] = array(
		      'data' => array(
		        l($node->name, 'qiye_exit_scheme_file/view/'. $node->id),
		        $node->upload_name,
		        format_date($node->timestamp, 'custom', 'Y-m-d'),
		        l('查看','qiye_exit_scheme_file/view/'. $node->id),
		      )
		      );
		  }
	}
  
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

//选择企业
function qiye_exit_scheme_file_qiyelist_page($fund_id) {
  $html = '';	
  $html .= l('返回基金列表','qiye_exit_scheme_file/fundlist/') .  '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
  $html .= l('添加被投企业信息','beitouqiye/create/'.$fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $html .= l('导出','beitouqiye/exportcsv/'.$fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $options = array(
  'target_id' => 'printable_div',
  'value' => t('Print'),
  'type' => 'link',
  'custom_css' => drupal_get_path('module','my_module').'/css/print.css',
  );

  $html .= area_print_form($options). '<br />'. '<br />';
  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$html .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  $html .= '<div id="printable_div">';
  $header = array(
      array('data' => '序号'),
      array('data' => '被投企业名称', 'field' => 'company_name'),
      //array('data' => '投资时间', 'field' => 'touzi_timestamp'),
      array('data' => '投资额(万元)', 'field' => 'touzi_money'),
      array('data' => '占股比例', 'field' => 'zhangu_percentage'),
      array('data' => '发展阶段', 'field' => 'fazhanjieduan'),
      array('data' => '退出方案管理'),
      array('data' => '退出方案管理'),
      array('data' => '退出信息管理（重要）'),
      );
  $query = db_select('beitouqiye_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(20)//20 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'company_name',
      'touzi_timestamp',
      'touzi_money',
      'zhangu_percentage',
      'fazhanjieduan',
      ))
	  ->condition('fund_id',$fund_id,'=');
  $results = $query
      ->execute();

  $rows1 = array();
  $rows2 = array();
  $serial_num1 = 1;
  $serial_num2 = 1;
  foreach ($results as $node) {
  	  $query = "SELECT id FROM " .
           "{company_exit_info} where beitouqiye_id = ?";
	  $queryResult = db_query($query, array($node->id));
	  $beitouqiye_id = '';
	  foreach($queryResult as $result){
	  	$beitouqiye_id = $result->id;
	  }
	  if($beitouqiye_id>0){
	  	$rows1[] = array(
	      'data' => array(
	        $serial_num1,
	        l($node->company_name, 'beitouqiye/list/'. $node->id),
	        //format_date($node->touzi_timestamp, 'custom', 'Y-m-d'),
	        $node->touzi_money,
	        $node->zhangu_percentage,
	        $node->fazhanjieduan,
	         l('进入', 'qiye_exit_scheme_file/qiyelist/'. $node->id),
	         l('进入', 'qiye_exit_scheme_file/qiyelist/'. $node->id),
	         l('查看', 'company_exit/list/'. $beitouqiye_id),
	      )
	      );
		  $serial_num1++;
	  }

	  else{
	  	$rows2[] = array(
	      'data' => array(
	        $serial_num2,
	        l($node->company_name, 'beitouqiye/list/'. $node->id),
	        //format_date($node->touzi_timestamp, 'custom', 'Y-m-d'),
	        $node->touzi_money,
	        $node->zhangu_percentage,
	        $node->fazhanjieduan,
	         l('进入', 'qiye_exit_scheme_file/qiyelist/'. $node->id),
	         l('进入', 'qiye_exit_scheme_file/qiyelist/'. $node->id),
	         l('填写', 'company_exit/create/'. $node->id),
	      )
	      );
		  $serial_num2++;
	  }     
  }
  $html .= '已退出企业列表<br>';
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows1,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有已退出企业信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  $html .= '未退出企业列表<br>';
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows2,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有未退出企业信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  $html .= '</div>';
  return ($html); 
}

//项目退出方案设置基金选择入口
function qiye_exit_scheme_file_fundlist_page() {
 $html = '';
 $header = array(
      array('data' => '基金名称', 'field' => 'registered_name', 'sort' => 'desc'),
      array('data' => '项目名称', 'field' => 'xiangmu_set'),
      array('data' => '退出方案管理', 'field' => 'beitouqiye_set'),
      );
  $query = db_select('fund_basic_information', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'registered_name',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
  			$query_xiangmu = db_select('xiangmu_info', 'n')
		      ->fields ('n', array (
		      'id',
		      'company_name',
		      ))
			  ->condition('fund_id',$node->id,'=');  
		  $results_xiangmu = $query_xiangmu
		      ->execute();
		  foreach ($results_xiangmu as $xiangmu) {
			  $rows[] = array(
		      'data' => array(
		        $node->registered_name,
		        $xiangmu->company_name,
		        l('查看', 'qiye_exit_scheme_file/qiyelist/'.$xiangmu->id),
		      )
		      );
			}
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有项目信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}
